List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:com.vossoftware.app.goldstockexchangev3.server.FriendlyPingServer.java
License:Open Source License
/** * Send client list to newly registered client. When a new client is registered, that client must * be informed about the other registered clients. * * @param client Newly registered client. *//* w w w. j av a 2s . c o m*/ private void sendClientList(Client client) { ArrayList<Client> clientList = new ArrayList(); for (Entry<String, Client> clientEntry : clientMap.entrySet()) { Client currentClient = clientEntry.getValue(); if (currentClient.registrationToken != client.registrationToken) { clientList.add(currentClient); } } JsonElement clientElements = gson.toJsonTree(clientList, new TypeToken<Collection<Client>>() { }.getType()); if (clientElements.isJsonArray()) { JsonObject jSendClientList = new JsonObject(); JsonObject jData = new JsonObject(); jData.addProperty(ACTION_KEY, Constants.ACTION_SEND_CLIENT_LIST); jData.add(CLIENTS_KEY, clientElements); jSendClientList.add(DATA_KEY, jData); friendlyGcmServer.send(client.registrationToken, jSendClientList); } }
From source file:com.wialon.core.MessagesLoader.java
License:Apache License
private void onMessagesReceived(String response, ResponseHandler callback) { if (response != null) { callback.onSuccess(response);//w ww . j av a 2s . c o m JsonElement jsonElement = Session.getInstance().getJsonParser().parse(response); JsonArray messagesArray; if (jsonElement.isJsonObject()) messagesArray = jsonElement.getAsJsonObject().get("messages").getAsJsonArray(); else if (jsonElement.isJsonArray()) messagesArray = jsonElement.getAsJsonArray(); else return; Message[] messages = new Message[messagesArray.size()]; for (int i = 0; i < messagesArray.size(); i++) { JsonElement messageElement = messagesArray.get(i); if (messageElement.isJsonObject() && messageElement.getAsJsonObject().has("f") && messageElement.getAsJsonObject().has("f")) { String tp = messageElement.getAsJsonObject().get("tp").getAsString(); long f = messageElement.getAsJsonObject().get("f").getAsLong(); Message.messageFlag flag = Message.messageFlag.getMessageFlag(f); if (flag == null) continue; Class clazz = Message.MessageType.getMessageClass(flag, tp); if (clazz != null) messages[i] = (Message) Session.getInstance().getGson().fromJson(messageElement, clazz); } } if (callback instanceof MessagesResponseHandler) ((MessagesResponseHandler) callback).onSuccessMessages(messages); return; } callback.onFailure(6, null); }
From source file:com.wialon.core.Session.java
License:Apache License
/** * Handle items search result from server * callback require 2nd parameter in form: {items: [], dataFlags: 0x10, totalItemsCount: 100, indexFrom: 0, indexTo: 9, searchSpec: {...}} *//* w w w . j a v a 2s .c om*/ private void onSearchItemsResult(String result, ResponseHandler callback) { if (result == null) { callback.onFailure(6, null); return; } //Send string result callback.onSuccess(result); // construct items JsonElement responseJson = jsonParser.parse(result); if (responseJson == null || !responseJson.isJsonObject()) { return; } JsonElement dataFlags = responseJson.getAsJsonObject().get("dataFlags"); JsonElement itemsJson = responseJson.getAsJsonObject().get("items"); if (itemsJson == null || !itemsJson.isJsonArray() || dataFlags == null || dataFlags.getAsNumber() == null) { return; } JsonArray responseItems = itemsJson.getAsJsonArray(); Item[] items = new Item[responseItems.size()]; for (int i = 0; i < responseItems.size(); i++) { try { JsonObject itemData = responseItems.get(i).getAsJsonObject(); Item item = constructItem(itemData, dataFlags.getAsLong()); items[i] = item; } catch (Exception e) { e.printStackTrace(); } } if (callback instanceof SearchResponseHandler) ((SearchResponseHandler) callback).onSuccessSearch(items); }
From source file:com.wialon.core.Session.java
License:Apache License
private void onDataFlagsUpdated(String result, ResponseHandler callback) { if (result == null) { if (callback != null) callback.onFailure(6, null); return;//w w w .j av a 2 s . c om } JsonElement responseJson = jsonParser.parse(result); if (responseJson == null || !responseJson.isJsonArray()) { callback.onFailure(6, null); return; } JsonArray responseItems = ((JsonArray) responseJson); // iterate over returned array for (int i = 0; i < responseItems.size(); i++) { try { // update items data, construct new items long itemId = responseItems.get(i).getAsJsonObject().get("i").getAsLong(); long itemFlags = responseItems.get(i).getAsJsonObject().get("f").getAsLong(); JsonObject itemData = null; if (responseItems.get(i).getAsJsonObject().get("d").isJsonObject()) itemData = responseItems.get(i).getAsJsonObject().get("d").getAsJsonObject(); // check if we need to construct this item Item item = itemsById.get(itemId); if (item == null && itemFlags != 0 && itemData != null) { // construct item item = constructItem(itemData, itemFlags); if (item != null) registerItem(item); } else { // remove item if (itemFlags == 0) removeItem(item); else { if (item == null) continue; // update item if (itemData != null) updateItem(item, itemData); item.setDataFlags(itemFlags); } } } catch (Exception e) { e.printStackTrace(); callback.onFailure(6, e); } } callback.onSuccess(result); }
From source file:com.wialon.item.prop.ItemProperties.java
License:Apache License
/** * Handle result of update property item * @param callback callback function// www. jav a 2s. c om * @param result json in form [Integer(id), Object or null] * @param skipFlag skip */ private void modifyProperties(String result, ResponseHandler callback, boolean skipFlag) { if (result != null) { JsonElement jsonResult = Session.getInstance().getJsonParser().parse(result); JsonArray jsonArrayResult; if (data != null && jsonResult.isJsonArray() && (jsonArrayResult = jsonResult.getAsJsonArray()).size() == 2) { String id = jsonArrayResult.get(0).toString(); String newData = null; if (!jsonArrayResult.get(1).isJsonNull()) newData = jsonArrayResult.get(1).toString(); String oldData = data.get(id); if (newData != null) // update/create item data.put(id, newData); else if (oldData != null && !skipFlag) data.remove(id); // fire property update event if (!skipFlag && !String.valueOf(newData).equals(String.valueOf(oldData))) item.fireItemPropertyEvent(event, oldData, newData); if (callback != null) callback.onSuccess(result); return; } } if (callback != null) callback.onFailure(6, null); }
From source file:com.wialon.item.Unit.java
License:Apache License
@Override public boolean updateItemData(String key, JsonElement data) { if (super.updateItemData(key, data)) return true; else {/* w ww . j ava 2 s . c o m*/ if (key.equals("uid") && data.getAsString() != null) { setUniqueId(data.getAsString()); } else if (key.equals("hw") && data.getAsNumber() != null) { setDeviceTypeId(data.getAsLong()); } else if (key.equals("ph") && data.getAsString() != null) { setPhoneNumber(data.getAsString()); } else if (key.equals("ph2") && data.getAsString() != null) { setPhoneNumber2(data.getAsString()); } else if (key.equals("psw") && data.getAsString() != null) { setAccessPassword(data.getAsString()); } else if (key.equals("cmds") && data.isJsonArray()) { setCommands(Session.getInstance().getGson().fromJson(data, List.class)); } else if (key.equals("pos") && data.isJsonObject()) { setPosition(Session.getInstance().getGson().fromJson(data, UnitData.Position.class)); } else if (key.equals("lmsg") && data.isJsonObject()) { setLastMessage(Session.getInstance().getGson().fromJson(data, UnitData.class)); } else if (key.equals("cfl") && data.getAsNumber() != null) { setCalcFlags(data.getAsLong()); } else if (key.equals("cnm") && data.getAsNumber() != null) { setMileageCounter(data.getAsLong()); } else if (key.equals("cneh") && data.getAsNumber() != null) { setEngineHoursCounter(data.getAsLong()); } else if (key.equals("cnkb") && data.getAsNumber() != null) { setTrafficCounter(data.getAsLong()); } else if (key.equals("prms") && data.isJsonObject()) { Map<String, Object> dataParams = new HashMap<String, Object>(); dataParams = Session.getInstance().getGson().fromJson(data, dataParams.getClass()); Map<String, Object> oldParams = getMessageParams(); if (oldParams == null) oldParams = new HashMap<String, Object>(); for (Map.Entry<String, Object> entry : dataParams.entrySet()) { if (entry.getValue() instanceof Number) { Object oldParam = oldParams.get(entry.getKey()); if (oldParam != null && oldParam instanceof Map) ((Map) oldParam).put("at", ((Number) entry.getValue()).longValue()); } else { oldParams.put(entry.getKey(), entry.getValue()); } } setMessageParams(oldParams); } else return false; return true; } }
From source file:com.wibidata.wibidota.DotaMatchBulkImporter.java
License:Apache License
private Player extractPlayer(JsonObject playerData) { Player.Builder builder = Player.newBuilder(); // Set the abilityUpgrades q final List<AbilityUpgrade> abilityUpgrades = new ArrayList<AbilityUpgrade>(); final JsonElement uncastAbilities = playerData.get("ability_upgrades"); // This can be null (players have no abilities selected yet?) use a 0 length list if (uncastAbilities != null) { for (JsonElement o : uncastAbilities.getAsJsonArray()) { abilityUpgrades.add(extractAbility(o.getAsJsonObject())); }//from w w w . j a va 2s . com } builder.setAbilityUpgrades(abilityUpgrades); // Set the additionalUnit JsonElement additionalUnitsElem = playerData.get("additional_units"); if (additionalUnitsElem == null) { builder.setAdditionalUnits(null); } else { final JsonObject additionalUnit; // This is sometimes contained in a list if (additionalUnitsElem.isJsonArray()) { additionalUnit = additionalUnitsElem.getAsJsonArray().get(0).getAsJsonObject(); } else { additionalUnit = additionalUnitsElem.getAsJsonObject(); } builder.setAdditionalUnits( AdditionalUnit.newBuilder().setName(additionalUnit.get("unitname").getAsString()) .setItemIds(readItems(additionalUnit)).build()); } return builder.setAccountId(getNullableLong(playerData.get("account_id"))) .setAssists(playerData.get("assists").getAsInt()).setDeaths(playerData.get("deaths").getAsInt()) .setDenies(playerData.get("denies").getAsInt()) .setExpPerMinute(playerData.get("xp_per_min").getAsDouble()) .setHeroId(playerData.get("hero_id").getAsInt()).setLastHits(playerData.get("last_hits").getAsInt()) .setLeaverStatus(getNullableInt(playerData.get("leaver_status"))) .setLevel(playerData.get("level").getAsInt()) .setPlayerSlot(playerData.get("player_slot").getAsInt()) .setTowerDamage(playerData.get("tower_damage").getAsInt()) .setGoldSpent(playerData.get("gold_spent").getAsInt()).setGold(playerData.get("gold").getAsInt()) .setGoldPerMinute(playerData.get("gold_per_min").getAsDouble()) .setHeroDamage(playerData.get("hero_damage").getAsInt()) .setHeroHealing(playerData.get("hero_healing").getAsInt()) .setKills(playerData.get("kills").getAsInt()).setItemIds(readItems(playerData)).build(); }
From source file:cosmos.records.JsonRecords.java
License:Apache License
public static List<MapRecord> parseAsMap(String json, DocIdGenerator generator) throws JsonSyntaxException { Preconditions.checkNotNull(json);/*from ww w. j a v a 2 s .c o m*/ Preconditions.checkNotNull(generator); JsonParser parser = new JsonParser(); JsonElement topLevelElement = parser.parse(json); if (topLevelElement.isJsonNull()) { return Collections.emptyList(); } else if (!topLevelElement.isJsonArray()) { throw new JsonSyntaxException("Expected a list of dictionaries"); } final LinkedList<MapRecord> records = Lists.newLinkedList(); // Walk the top level list JsonArray list = topLevelElement.getAsJsonArray(); for (JsonElement e : list) { // Make sure that it's a Json Object if (!e.isJsonObject()) { throw new JsonSyntaxException("Expected a Json Object"); } // Parse each "Object" (map) JsonObject map = e.getAsJsonObject(); records.add(asMapRecord(map, generator)); } return records; }
From source file:cosmos.records.JsonRecords.java
License:Apache License
public static List<MultimapRecord> parseAsMultimap(String json, DocIdGenerator generator) throws JsonSyntaxException { Preconditions.checkNotNull(json);//from w w w.j a va 2 s. c o m Preconditions.checkNotNull(generator); JsonParser parser = new JsonParser(); JsonElement topLevelElement = parser.parse(json); if (topLevelElement.isJsonNull()) { return Collections.emptyList(); } else if (!topLevelElement.isJsonArray()) { throw new JsonSyntaxException("Expected a list of dictionaries"); } final LinkedList<MultimapRecord> records = Lists.newLinkedList(); // Walk the top level list JsonArray list = topLevelElement.getAsJsonArray(); for (JsonElement e : list) { // Make sure that it's a Json Object if (!e.isJsonObject()) { throw new JsonSyntaxException("Expected a Json Object"); } // Parse each "Object" (map) JsonObject map = e.getAsJsonObject(); records.add(asMultimapRecord(map, generator)); } return records; }
From source file:cosmos.records.JsonRecords.java
License:Apache License
/** * Builds a {@link MultimapRecord} from the provided {@link JsonObject} using a docid * from the {@link DocIdGenerator}. This method will support lists of values for a key * in the {@link JsonObject} but will fail on values which are {@link JsonObject}s and * values which have nested {@link JsonArray}s. * @param map The {@link JsonObject} to build this {@link MultimapRecord} from * @param generator {@link DocIdGenerator} to construct a docid for this {@link MultimapRecord} * @return A {@link MultimapRecord} built from the provided arguments. *//*from ww w . j ava 2 s. co m*/ protected static MultimapRecord asMultimapRecord(JsonObject map, DocIdGenerator generator) { Multimap<Column, RecordValue<?>> data = HashMultimap.create(); for (Entry<String, JsonElement> entry : map.entrySet()) { final Column key = Column.create(entry.getKey()); final JsonElement value = entry.getValue(); if (value.isJsonNull()) { data.put(key, null); } else if (value.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) value; // Numbers if (primitive.isNumber()) { NumberRecordValue<?> v; double d = primitive.getAsDouble(); if ((int) d == d) { v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS); } else if ((long) d == d) { v = new LongRecordValue((long) d, Defaults.EMPTY_VIS); } else { v = new DoubleRecordValue(d, Defaults.EMPTY_VIS); } data.put(key, v); } else if (primitive.isString()) { // String data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS)); } else if (primitive.isBoolean()) { // Boolean data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS)); } else if (primitive.isJsonNull()) { // Is this redundant? data.put(key, null); } else { throw new RuntimeException("Unhandled primitive: " + primitive); } } else if (value.isJsonArray()) { // Multimaps should handle the multiple values, not fail JsonArray values = value.getAsJsonArray(); for (JsonElement element : values) { if (element.isJsonNull()) { data.put(key, null); } else if (element.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) element; // Numbers if (primitive.isNumber()) { NumberRecordValue<?> v; double d = primitive.getAsDouble(); if ((int) d == d) { v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS); } else if ((long) d == d) { v = new LongRecordValue((long) d, Defaults.EMPTY_VIS); } else { v = new DoubleRecordValue(d, Defaults.EMPTY_VIS); } data.put(key, v); } else if (primitive.isString()) { // String data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS)); } else if (primitive.isBoolean()) { // Boolean data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS)); } else if (primitive.isJsonNull()) { // Is this redundant? data.put(key, null); } else { throw new RuntimeException("Unhandled Json primitive: " + primitive); } } else { throw new RuntimeException("Expected a Json primitive"); } } } else { throw new RuntimeException("Expected a String, Number or Boolean"); } } return new MultimapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS); }