Java Code Examples for com.google.gson.JsonArray#get()
The following examples show how to use
com.google.gson.JsonArray#get() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JSONDetailedGroupInfoImpl.java From smarthome with Eclipse Public License 2.0 | 6 votes |
/** * Creates a new {@link JSONDetailedGroupInfoImpl} through the {@link JsonObject}. * * @param jObject of the server response, must not be null */ public JSONDetailedGroupInfoImpl(JsonObject jObject) { this.deviceList = new LinkedList<String>(); if (jObject.get(JSONApiResponseKeysEnum.NAME.getKey()) != null) { name = jObject.get(JSONApiResponseKeysEnum.NAME.getKey()).getAsString(); } if (jObject.get(JSONApiResponseKeysEnum.ID.getKey()) != null) { this.groupId = jObject.get(JSONApiResponseKeysEnum.ID.getKey()).getAsShort(); } if (jObject.get(JSONApiResponseKeysEnum.DEVICES.getKey()) instanceof JsonArray) { JsonArray array = (JsonArray) jObject.get(JSONApiResponseKeysEnum.DEVICES.getKey()); for (int i = 0; i < array.size(); i++) { if (array.get(i) != null) { deviceList.add(array.get(i).getAsString()); } } } }
Example 2
Source File: JsonUtil.java From p4ic4idea with Apache License 2.0 | 6 votes |
public static int[] getNullableIntArrayKey(JsonObject obj, String key) throws ResponseFormatException { JsonArray vay = getNullableArrayKey(obj, key); if (vay == null) { return null; } int[] ret = new int[vay.size()]; for (int i = 0; i < vay.size(); i++) { JsonElement vi = vay.get(i); if (vi.isJsonPrimitive()) { try { ret[i] = vi.getAsInt(); } catch (NumberFormatException e) { throw new ResponseFormatException(key + '[' + i + ']', vi, e); } } else { throw new ResponseFormatException(key + '[' + i + ']', vi); } } return ret; }
Example 3
Source File: JsonUtil.java From olca-app with Mozilla Public License 2.0 | 6 votes |
private static boolean equal(String property, JsonArray a1, JsonArray a2, ElementFinder finder) { if (a1.size() != a2.size()) return false; Iterator<JsonElement> it1 = a1.iterator(); Set<Integer> used = new HashSet<>(); while (it1.hasNext()) { JsonElement e1 = it1.next(); int index = finder.find(property, e1, a2, used); if (index == -1) return false; JsonElement e2 = a2.get(index); if (!equal(property, e1, e2, finder)) return false; used.add(index); } return true; }
Example 4
Source File: JsonLoader.java From asteria-3.0 with GNU General Public License v3.0 | 6 votes |
/** * Loads the parsed data. How the data is loaded is defined by * {@link JsonLoader#load(JsonObject, Gson)}. * * @return the loader instance, for chaining. */ public final JsonLoader load() { try (FileReader in = new FileReader(Paths.get(path).toFile())) { JsonParser parser = new JsonParser(); JsonArray array = (JsonArray) parser.parse(in); Gson builder = new GsonBuilder().create(); for (int i = 0; i < array.size(); i++) { JsonObject reader = (JsonObject) array.get(i); load(reader, builder); } } catch (Exception e) { e.printStackTrace(); } return this; }
Example 5
Source File: PropsTableViewTest.java From karyon with Apache License 2.0 | 6 votes |
@Test public void sortKeyAscendingTest() { final PropsTableView ptv = new PropsTableView(); ptv.enableColumnSort(PropsTableView.KEY, false); // ascending sort final JsonArray data = ptv.getData(); assertTrue(data != null); int totalElms = data.size(); assertTrue(totalElms > 0); String prevKey = null; for (int i = 0; i < totalElms; i++) { final JsonElement propElm = data.get(i); final JsonArray propKVArray = propElm.getAsJsonArray(); final String propKey = propKVArray.get(0).getAsString(); assertTrue(propKVArray.size() == 2); if (prevKey == null) { prevKey = propKey; } else { // verify sorting order assertTrue(prevKey.compareTo(propKey) < 0); prevKey = propKey; } } }
Example 6
Source File: VulnerabilityRepository.java From pacbot with Apache License 2.0 | 5 votes |
/** * Gets the vulnerability by qid. * * @param qid * the qid * @return the vulnerability by qid */ public Map<String, Object> getVulnerabilityByQid(String qid) { StringBuilder urlToQuery = new StringBuilder(esUrl).append("/").append("qualys-kb/kb/_search"); StringBuilder requestBody = new StringBuilder( "{\"query\":{\"bool\":{\"must\":[{\"term\":{\"latest\":\"true\"}},{\"term\":{\"qid.keyword\":\""); requestBody.append(qid); requestBody.append("\"}}]}}}"); String responseJson = ""; try { responseJson = PacHttpUtils.doHttpPost(urlToQuery.toString(), requestBody.toString()); } catch (Exception e) { LOGGER.error("Error in getVulnerabilityByQid from ES", e); } JsonParser jsonParser = new JsonParser(); Map<String, Object> vuln = new HashMap<>(); if (StringUtils.isNotEmpty(responseJson)) { JsonObject resultJson = (JsonObject) jsonParser.parse(responseJson); JsonArray hits = resultJson.get("hits").getAsJsonObject().get("hits").getAsJsonArray(); if (hits.size() > 0) { for (int i = 0; i < hits.size(); i++) { JsonObject obj = (JsonObject) hits.get(i); JsonObject sourceJson = (JsonObject) obj.get("_source"); if (sourceJson != null) { vuln = new Gson().fromJson(sourceJson, new TypeToken<Map<String, Object>>() { }.getType()); vuln.remove("latest"); vuln.remove("_loadDate"); } } } } return vuln; }
Example 7
Source File: GsonJsonRpcUnmarshaller.java From che with Eclipse Public License 2.0 | 5 votes |
private List<String> getArray(String message, boolean isArray) { if (!isArray) { return singletonList(message); } JsonArray jsonArray = jsonParser.parse(message).getAsJsonArray(); int size = jsonArray.size(); List<String> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { JsonElement jsonElement = jsonArray.get(i); result.add(jsonElement.toString()); } return result; }
Example 8
Source File: GSONUtils.java From micro-integrator with Apache License 2.0 | 5 votes |
/** * Function to convert GSON array model to generic array model. * * @param jsonElement gson array to transform * @return */ public static Object[] gsonJsonArrayToObjectArray(JsonElement jsonElement) { ArrayList<Object> jsonArrayList = new ArrayList<>(); if (jsonElement.isJsonArray()) { JsonArray jsonArray = jsonElement.getAsJsonArray(); for (int i = 0; i < jsonArray.size(); i++) { JsonElement arrayElement = jsonArray.get(i); if (arrayElement.isJsonPrimitive()) { JsonPrimitive jsonPrimitive = arrayElement.getAsJsonPrimitive(); if (jsonPrimitive.isString()) { jsonArrayList.add(jsonPrimitive.getAsString()); } else if (jsonPrimitive.isBoolean()) { jsonArrayList.add(jsonPrimitive.getAsBoolean()); } else if (jsonPrimitive.isNumber()) { jsonArrayList.add(jsonPrimitive.getAsNumber()); } else { //unknown type log.warn("Unknown JsonPrimitive type found : " + jsonPrimitive.toString()); } } else if (arrayElement.isJsonObject()) { jsonArrayList.add(gsonJsonObjectToMap(arrayElement)); } else if (arrayElement.isJsonArray()) { jsonArrayList.add(gsonJsonArrayToObjectArray(arrayElement.getAsJsonArray())); } else { // remaining JsonNull jsonArrayList.add(null); } } } else { //Not a JsonObject hence return empty array log.error("Provided gson model does not represent json array"); } return jsonArrayList.toArray(); }
Example 9
Source File: DsAPIImpl.java From smarthome with Eclipse Public License 2.0 | 5 votes |
@Override public List<String> getMeterList(String token) { List<String> meterList = new LinkedList<String>(); JsonObject responseObj = query(token, QUERY_GET_METERLIST); if (responseObj != null && responseObj.get(JSONApiResponseKeysEnum.DS_METERS.getKey()).isJsonArray()) { JsonArray array = responseObj.get(JSONApiResponseKeysEnum.DS_METERS.getKey()).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { if (array.get(i) instanceof JsonObject) { meterList.add(array.get(i).getAsJsonObject().get("dSID").getAsString()); } } } return meterList; }
Example 10
Source File: GoogleServicesTask.java From play-services-plugins with Apache License 2.0 | 5 votes |
/** * find an item in the "client" array that match the package name of the app * * @param jsonObject the root json object. * @return a JsonObject representing the client entry or null if no match is found. */ private JsonObject getClientForPackageName(JsonObject jsonObject) { JsonArray array = jsonObject.getAsJsonArray("client"); if (array != null) { final int count = array.size(); for (int i = 0; i < count; i++) { JsonElement clientElement = array.get(i); if (clientElement == null || !clientElement.isJsonObject()) { continue; } JsonObject clientObject = clientElement.getAsJsonObject(); JsonObject clientInfo = clientObject.getAsJsonObject("client_info"); if (clientInfo == null) continue; JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info"); if (androidClientInfo == null) continue; JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name"); if (clientPackageName == null) continue; if (getPackageName().equals(clientPackageName.getAsString())) { return clientObject; } } } return null; }
Example 11
Source File: SceneDiscovery.java From smarthome with Eclipse Public License 2.0 | 5 votes |
private void addScenesToList(JsonObject resultJsonObj) { if (resultJsonObj.get(JSONApiResponseKeysEnum.ZONES.getKey()) != null && resultJsonObj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) { JsonArray zones = resultJsonObj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray(); for (int i = 0; i < zones.size(); i++) { if (((JsonObject) zones.get(i)).get(JSONApiResponseKeysEnum.GROUPS.getKey()).isJsonArray()) { JsonArray groups = ((JsonObject) zones.get(i)).get(JSONApiResponseKeysEnum.GROUPS.getKey()) .getAsJsonArray(); for (int j = 0; j < groups.size(); j++) { if (((JsonObject) groups.get(j)).get("scenes") != null && ((JsonObject) groups.get(j)).get("scenes").isJsonArray()) { JsonArray scenes = ((JsonObject) groups.get(j)).get("scenes").getAsJsonArray(); for (int k = 0; k < scenes.size(); k++) { if (scenes.get(k).isJsonObject()) { JsonObject sceneJsonObject = ((JsonObject) scenes.get(k)); int zoneID = ((JsonObject) zones.get(i)).get("ZoneID").getAsInt(); short groupID = ((JsonObject) groups.get(j)).get("group").getAsShort(); InternalScene scene = new InternalScene(zoneID, groupID, sceneJsonObject.get("scene").getAsShort(), sceneJsonObject.get("name").getAsString()); if (genList) { this.namedScenes.add(scene); } else { sceneDiscoverd(scene); } } } } } } } } }
Example 12
Source File: WxBot.java From WxBot with GNU General Public License v3.0 | 5 votes |
private String getSyncKeyStr() { String syncKeyTmp = ""; JsonArray jsonArray = syncKeyJsonObject.getAsJsonArray("List"); for (int i = 0; i < jsonArray.size(); i++) { JsonObject obj = (JsonObject) jsonArray.get(i); syncKeyTmp += obj.get("Key") + "_" + obj.get("Val") + "|"; } if (syncKeyTmp.length() > 0) { syncKeyTmp = syncKeyTmp.substring(0, syncKeyTmp.length() - 1); } return syncKeyTmp; }
Example 13
Source File: DeserializerFilters.java From openshop.io-android with MIT License | 4 votes |
@Override public Filters deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Check if whole object is available if (json.isJsonArray()) { final Filters filters = new Filters(); List<FilterType> filterList = new ArrayList<>(); JsonArray jArray = (JsonArray) json; for (int i = 0; i < jArray.size(); i++) { JsonElement jElement = jArray.get(i); if (jElement.isJsonObject()) { JsonObject jObject = (JsonObject) jElement; if (jObject.has(TAG_TYPE)) { String type = jObject.get(TAG_TYPE).getAsString(); switch (type) { case FILTER_TYPE_COLOR: final FilterTypeColor filterTypeColor = new FilterTypeColor(); filterTypeColor.setType(FILTER_TYPE_COLOR); parseGeneralFields(jObject, filterTypeColor); filterTypeColor.setValues(parseTypeValues(FilterValueColor.class, jObject, context)); if (filterTypeColor.getValues() != null) { filterList.add(filterTypeColor); } break; case FILTER_TYPE_SELECT: final FilterTypeSelect filterTypeSelect = new FilterTypeSelect(); filterTypeSelect.setType(FILTER_TYPE_SELECT); parseGeneralFields(jObject, filterTypeSelect); filterTypeSelect.setValues(parseTypeValues(FilterValueSelect.class, jObject, context)); if (filterTypeSelect.getValues() != null) { filterList.add(filterTypeSelect); } break; case FILTER_TYPE_RANGE: final FilterTypeRange filterTypeRange = new FilterTypeRange(); filterTypeRange.setType(FILTER_TYPE_RANGE); parseGeneralFields(jObject, filterTypeRange); if (jObject.has(TAG_VALUES)) { JsonArray rangeValues = jObject.get(TAG_VALUES).getAsJsonArray(); if (rangeValues != null && rangeValues.size() == 3) { filterTypeRange.setMin(rangeValues.get(0).getAsInt()); filterTypeRange.setMax(rangeValues.get(1).getAsInt()); filterTypeRange.setRangeTitle(rangeValues.get(2).getAsString()); } } filterList.add(filterTypeRange); break; } } } } if (!filterList.isEmpty()) filters.setFilters(filterList); return filters; } throw new JsonParseException("Unexpected JSON type: " + json.getClass().getSimpleName()); }
Example 14
Source File: HarFileHandler.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
private JsonObject getEntry() { JsonObject log = (JsonObject)this.harJson.get("log"); JsonArray entries = (JsonArray)log.get("entries"); return (JsonObject)entries.get(0); }
Example 15
Source File: HarFileHandler.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
private JsonObject getEntry() { JsonObject log = (JsonObject)this.harJson.get("log"); JsonArray entries = (JsonArray)log.get("entries"); return (JsonObject)entries.get(0); }
Example 16
Source File: HarFileHandler.java From freehealth-connector with GNU Affero General Public License v3.0 | 4 votes |
private JsonObject getEntry() { JsonObject log = (JsonObject)this.harJson.get("log"); JsonArray entries = (JsonArray)log.get("entries"); return (JsonObject)entries.get(0); }
Example 17
Source File: MessageUtils.java From kurento-java with Apache License 2.0 | 4 votes |
private static <R> R convertJsonTo(JsonElement resultJsonObject, Class<R> resultClass) { if (resultJsonObject == null) { return null; } if (resultClass == null) { return null; } R resultR = null; if (resultClass == String.class || resultClass == Boolean.class || resultClass == Character.class || Number.class.isAssignableFrom(resultClass) || resultClass.isPrimitive()) { JsonElement value; if (resultJsonObject.isJsonObject()) { Set<Entry<String, JsonElement>> properties = ((JsonObject) resultJsonObject).entrySet(); if (properties.size() > 1) { Entry<String, JsonElement> prop = properties.iterator().next(); log.warn( "Converting a result with {} properties in a value" + " of type {}. Selecting propoerty '{}'", Integer.valueOf(properties.size()), resultClass, prop.getKey()); value = prop.getValue(); } else if (properties.size() == 1) { value = properties.iterator().next().getValue(); } else { value = null; } } else if (resultJsonObject.isJsonArray()) { JsonArray array = (JsonArray) resultJsonObject; if (array.size() > 1) { log.warn( "Converting an array with {} elements in a value " + "of type {}. Selecting first element", Integer.valueOf(array.size()), resultClass); } value = array.get(0); } else { value = resultJsonObject; } resultR = getGson().fromJson(value, resultClass); } else { resultR = getGson().fromJson(resultJsonObject, resultClass); } return resultR; }
Example 18
Source File: RecommendationsRepository.java From pacbot with Apache License 2.0 | 4 votes |
public Map<String, Object> getSummaryByApplication(String assetGroup) throws DataException { Map<String,Object> result = new HashMap<>(); List<Map<String,Object>> summaryByApplication = new ArrayList<>(); Double totalMonthlySavings = 0.0; StringBuilder urlToQuery = new StringBuilder(esUrl).append("/").append(assetGroup).append("/").append(Constants.SEARCH); StringBuilder requestBody = new StringBuilder("{\"size\":0,\"query\":{\"bool\":{\"must\":[{\"match\":{\"latest\":true}},{\"match\":{\"_entity.keyword\":true}}]}}" + ",\"aggs\":{\"apps\":{\"terms\":{\"field\":\"tags.Application.keyword\",\"size\":100000},\"aggs\":{\"recommendations\":{\"children\":{\"type\":\"recommendation\"}" + ",\"aggs\":{\"latest\":{\"filter\":{\"match\":{\"latest\":true}},\"aggs\":{\"savings\":{\"sum\":{\"field\":\"monthlysavings\"}}}}}}}}}}"); String responseDetails; try { responseDetails = PacHttpUtils.doHttpPost(urlToQuery.toString(), requestBody.toString()); } catch (Exception e) { LOGGER.error("Error in getSummaryByApplication "+e); throw new DataException(e); } JsonParser parser = new JsonParser(); JsonObject responseDetailsjson = parser.parse(responseDetails).getAsJsonObject(); JsonObject aggregations = responseDetailsjson.get(Constants.AGGREGATIONS).getAsJsonObject(); JsonArray appsBuckets = aggregations.get("apps").getAsJsonObject().get(Constants.BUCKETS).getAsJsonArray(); if (appsBuckets.size() > 0) { for (int i=0; i<appsBuckets.size();i++) { JsonObject appObj = (JsonObject) appsBuckets.get(i); if (appObj != null) { JsonObject recommendationObj = appObj.get("recommendations").getAsJsonObject(); if(recommendationObj.has("latest") && recommendationObj.get("latest").getAsJsonObject().has("savings")) { Map<String,Object> app = new HashMap<>(); app.put("application", appObj.get(Constants.KEY).getAsString()); app.put("recommendations", recommendationObj.get(Constants.DOC_COUNT).getAsLong()); Double monthlySavings = recommendationObj.get("latest").getAsJsonObject().get("savings").getAsJsonObject().get(Constants.VALUE).getAsDouble(); totalMonthlySavings += monthlySavings; app.put("monthlySavings", Math.round(monthlySavings)); summaryByApplication.add(app); } } } } result.put("ag", assetGroup); result.put("totalMonthlySavings", Math.round(totalMonthlySavings)); result.put("applications", summaryByApplication); return result; }
Example 19
Source File: PacmanUtils.java From pacbot with Apache License 2.0 | 4 votes |
public static String getQueryDataForCheckid(String checkId, String esUrl, String id, String region, String accountId) throws Exception { JsonParser jsonParser = new JsonParser(); String resourceinfo = null; Map<String, Object> mustFilter = new HashMap<>(); Map<String, Object> mustNotFilter = new HashMap<>(); Map<String, List<String>> matchPhrasePrefix = new HashMap<>(); HashMultimap<String, Object> shouldFilter = HashMultimap.create(); Map<String, Object> mustTermsFilter = new HashMap<>(); mustFilter.put(PacmanRuleConstants.CHECK_ID_KEYWORD, checkId); mustFilter.put(PacmanRuleConstants.ACCOUNT_ID_KEYWORD, accountId); List<String> resourceInfoList = new ArrayList<>(); if (region != null) { resourceInfoList.add(region); } resourceInfoList.add(id); matchPhrasePrefix.put(PacmanRuleConstants.RESOURCE_INFO, resourceInfoList); JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(esUrl, mustFilter, mustNotFilter, shouldFilter, null, 0, mustTermsFilter, matchPhrasePrefix,null); if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) { JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString()); JsonArray jsonArray = hitsJson.getAsJsonObject().get(PacmanRuleConstants.HITS).getAsJsonArray(); if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { JsonObject firstObject = (JsonObject) jsonArray.get(i); JsonObject sourceJson = (JsonObject) firstObject.get(PacmanRuleConstants.SOURCE); if (sourceJson != null && sourceJson.has(PacmanRuleConstants.RESOURCE_INFO)) { if (sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).isJsonObject()) { resourceinfo = sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).getAsJsonObject() .toString(); } else { resourceinfo = sourceJson.get(PacmanRuleConstants.RESOURCE_INFO).getAsString(); } } } } } return resourceinfo; }
Example 20
Source File: IncrementalPullStrategy.java From azure-mobile-apps-android-client with Apache License 2.0 | 3 votes |
public void initialize() { JsonElement results = null; try { query.includeDeleted(); query.removeInlineCount(); query.removeProjection(); originalQuery = query; results = mStore.read( QueryOperations.tableName(INCREMENTAL_PULL_STRATEGY_TABLE) .field("id") .eq(table.getTableName() + "_" + queryId)); if (results != null) { JsonArray resultsArray = results.getAsJsonArray(); if (resultsArray.size() > 0) { JsonElement result = resultsArray.get(0); String stringMaxUpdatedDate = result.getAsJsonObject() .get("maxupdateddate").getAsString(); deltaToken = maxUpdatedAt = getDateFromString(stringMaxUpdatedDate); } } setupQuery(maxUpdatedAt); } catch (MobileServiceLocalStoreException e) { throw new RuntimeException(e); } }