Java Code Examples for com.google.gson.JsonObject#getAsJsonObject()
The following examples show how to use
com.google.gson.JsonObject#getAsJsonObject() .
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: ReverseNestedBuilder.java From flummi with Apache License 2.0 | 6 votes |
@Override public AggregationResult parseResponse(JsonObject jsonObject) { AggregationResult aggregation = null; JsonObject innerAggregation = jsonObject.getAsJsonObject(getName()); JsonElement bucketsElement = innerAggregation.get("buckets"); if (bucketsElement != null) { JsonArray bucketsArray = bucketsElement.getAsJsonArray(); ArrayList<Bucket> bucketList = new ArrayList<>(); for (JsonElement elem : bucketsArray) { JsonObject outerBucket = elem.getAsJsonObject(); JsonObject innerBucket = outerBucket.getAsJsonObject(getName()); if (innerBucket == null) { throw new RuntimeException("No reverse nested aggregation result for " + getName()); } bucketList.add(new Bucket(outerBucket.get("key").getAsString(), innerBucket.get("doc_count").getAsLong())); } aggregation = new BucketAggregationResult(bucketList); } return aggregation; }
Example 2
Source File: ProtobufUtilTest.java From ja-micro with Apache License 2.0 | 6 votes |
@Test public void protobufToJson_MessageWithMap_Success() throws Exception { // given FrameworkTest.MessageWithMap messageWithMap = FrameworkTest.MessageWithMap.newBuilder() .putErrorMap("first-error", FrameworkTest.Error.INVALID_VEHICLE_ID) .putErrorMap("second-error", FrameworkTest.Error.NO_ERROR) .build(); // when JsonObject jsonObject = ProtobufUtil.protobufToJson(messageWithMap); // then JsonObject error_map = jsonObject.getAsJsonObject("error_map"); assertThat(error_map.size()).isEqualTo(2); assertThat(error_map.getAsJsonPrimitive("first-error").getAsString()) .isEqualTo(FrameworkTest.Error.INVALID_VEHICLE_ID.toString()); assertThat(error_map.getAsJsonPrimitive("second-error").getAsString()) .isEqualTo(FrameworkTest.Error.NO_ERROR.toString()); }
Example 3
Source File: Adapters.java From activitystreams with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") public Range<?> deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { checkArgument(json.isJsonObject()); try { JsonObject obj = json.getAsJsonObject(); JsonObject upper = obj.getAsJsonObject("upper"); JsonObject lower = obj.getAsJsonObject("lower"); BoundType ubt = bt(upper.getAsJsonPrimitive("type")); BoundType lbt = bt(lower.getAsJsonPrimitive("type")); Object ub = des(upper.get("endpoint"),context); Object lb = des(lower.get("endpoint"),context); return Range.range((Comparable)lb, lbt, (Comparable)ub, ubt); } catch (Throwable t) { throw Throwables.propagate(t); } }
Example 4
Source File: PluginTemplateController.java From datax-web with Apache License 2.0 | 6 votes |
private void parse(FileReader reader) { JsonElement element = parser.parse(reader); // 获得 根节点 的实际 节点类型 JsonObject root = element.getAsJsonObject(); JsonPrimitive name = root.getAsJsonPrimitive("name"); JsonObject parameter = root.getAsJsonObject("parameter"); System.out.println("插件名称:" + name.getAsString()); //System.out.println(parameter.toString()); parseLoop("parameter", parameter.entrySet()); //JsonPrimitive nameJson = element.getAsJsonPrimitive("name"); //String name = nameJson.getAsString(); System.out.println("========================================================================================================================================"); System.out.println(root); //root.add("name",new JsonPrimitive("ddddddddddddddd")); //System.out.println(root); }
Example 5
Source File: TestUtils.java From yangtools with Eclipse Public License 1.0 | 5 votes |
static JsonObject childObject(final JsonObject jsonObject, final String... names) { for (final String name : names) { final JsonObject childJsonObject = jsonObject.getAsJsonObject(name); if (childJsonObject != null) { return childJsonObject; } } return null; }
Example 6
Source File: JSONUtil.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
public static JsonObject forceObject(JsonObject obj, String name) { if (obj.has(name) && obj.get(name).isJsonObject()) return obj.getAsJsonObject(name); if (obj.has(name)) obj.remove(name); JsonObject res = new JsonObject(); obj.add(name, res); return res; }
Example 7
Source File: ICD11Generator.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
private String readString(JsonObject obj, String name) { JsonObject p = obj.getAsJsonObject(name); if (p == null) { return null; } if (p.has("@value")) { return p.get("@value").getAsString(); } return null; }
Example 8
Source File: DVReportGenerator.java From jumbune with GNU Lesser General Public License v3.0 | 5 votes |
/** * Sets the regex violations. * * @param jobject refers to the json object * @param boardReport contains the regex violations that will be displayed on the dashboard. */ private void setRegexViolations(final JsonObject jobject, DataValidationDashBoardReport boardReport) { JsonObject jsonObject; jsonObject = jobject.getAsJsonObject(regexViolations); if (jsonObject == null) { return; } JsonElement element = jsonObject.getAsJsonObject(); boardReport.setRegexViolations((element.getAsJsonObject().get(TOTAL_VIOLATIONS).getAsString())); }
Example 9
Source File: SecurityAlertsInventoryCollector.java From pacbot with Apache License 2.0 | 5 votes |
public List<SecurityAlertsVH> fetchSecurityAlertsDetails(SubscriptionVH subscription) throws Exception { List<SecurityAlertsVH> securityAlertsList = new ArrayList<SecurityAlertsVH>(); String accessToken = azureCredentialProvider.getToken(subscription.getTenant()); String url = String.format(apiUrlTemplate, URLEncoder.encode(subscription.getSubscriptionId())); try { String response = CommonUtils.doHttpGet(url, "Bearer", accessToken); JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject(); JsonArray securityAlertsObjects = responseObj.getAsJsonArray("value"); for (JsonElement securityAlertsElement : securityAlertsObjects) { SecurityAlertsVH securityAlertsVH = new SecurityAlertsVH(); JsonObject databricksObject = securityAlertsElement.getAsJsonObject(); JsonObject properties = databricksObject.getAsJsonObject("properties"); securityAlertsVH.setId(databricksObject.get("id").getAsString()); securityAlertsVH.setName(databricksObject.get("name").getAsString()); securityAlertsVH.setType(databricksObject.get("type").getAsString()); securityAlertsVH.setSubscription(subscription.getSubscriptionId()); securityAlertsVH.setSubscriptionName(subscription.getSubscriptionName()); if (properties != null) { HashMap<String, Object> propertiesMap = new Gson().fromJson(properties.toString(), HashMap.class); securityAlertsVH.setPropertiesMap(propertiesMap); } securityAlertsList.add(securityAlertsVH); } } catch (Exception e) { log.error("Error collecting Security Alerts",e); } log.info("Target Type : {} Total: {} ","Security Alerts",securityAlertsList.size()); return securityAlertsList; }
Example 10
Source File: FileInfo.java From lancoder with GNU General Public License v3.0 | 5 votes |
/** * Construct file info from streams in json object. * * @param json * The json object from ffprobe * @param relativeSource * The relative path of the source file */ public FileInfo(JsonObject json, String relativeSource) { this.relativeSource = relativeSource; JsonObject format = json.get("format").getAsJsonObject(); this.setBitrate(format.get("bit_rate").getAsInt()); this.setSize(format.get("size").getAsLong()); // convert from seconds to ms this.setDuration((long) (format.get("duration").getAsDouble() * 1000)); this.setFormat(format.get("format_name").getAsString()); for (JsonElement jsonStream : json.get("streams").getAsJsonArray()) { JsonObject jsonObject = jsonStream.getAsJsonObject(); switch (jsonObject.get("codec_type").getAsString()) { case "video": JsonObject disposition = jsonObject.getAsJsonObject("disposition"); if (disposition == null || ! isAttachment(disposition)) { this.getStreams().add(new OriginalVideoStream(jsonObject, relativeSource, duration)); } break; case "audio": this.getStreams().add(new OriginalAudioStream(jsonObject, relativeSource, duration)); break; case "subtitle": this.getStreams().add(new TextStream(jsonObject, relativeSource)); break; default: break; } } }
Example 11
Source File: MappingData.java From ViaVersion with MIT License | 5 votes |
public static void init() { Via.getPlatform().getLogger().info("Loading 1.14.4 -> 1.15 mappings..."); JsonObject diffmapping = MappingDataLoader.loadData("mappingdiff-1.14to1.15.json"); JsonObject mapping1_14 = MappingDataLoader.loadData("mapping-1.14.json", true); JsonObject mapping1_15 = MappingDataLoader.loadData("mapping-1.15.json", true); oldToNewItems.defaultReturnValue(-1); blockStateMappings = new Mappings(mapping1_14.getAsJsonObject("blockstates"), mapping1_15.getAsJsonObject("blockstates"), diffmapping.getAsJsonObject("blockstates")); blockMappings = new Mappings(mapping1_14.getAsJsonObject("blocks"), mapping1_15.getAsJsonObject("blocks")); MappingDataLoader.mapIdentifiers(oldToNewItems, mapping1_14.getAsJsonObject("items"), mapping1_15.getAsJsonObject("items")); soundMappings = new Mappings(mapping1_14.getAsJsonArray("sounds"), mapping1_15.getAsJsonArray("sounds"), false); }
Example 12
Source File: KcaApiData.java From kcanotify with GNU General Public License v3.0 | 5 votes |
public static String getCurrentNodeAlphabet(int maparea, int mapno, int no) { String currentMapString = KcaUtils.format("%d-%d", maparea, mapno); String no_str = String.valueOf(no); if (helper != null) { JsonObject mapEdgeInfo = helper.getJsonObjectValue(DB_KEY_MAPEDGES); if (mapEdgeInfo != null && mapEdgeInfo.has(currentMapString)) { JsonObject currentMapInfo = mapEdgeInfo.getAsJsonObject(currentMapString); if (currentMapInfo.has(no_str)) { JsonArray nodeInfo = currentMapInfo.getAsJsonArray(no_str); no_str = nodeInfo.get(1).getAsString(); } } } return no_str; }
Example 13
Source File: GoogleServicesTask.java From play-services-plugins with Apache License 2.0 | 5 votes |
private void handleFirebaseUrl(JsonObject rootObject, Map<String, String> resValues) throws IOException { JsonObject projectInfo = rootObject.getAsJsonObject("project_info"); if (projectInfo == null) { throw new GradleException("Missing project_info object"); } JsonPrimitive firebaseUrl = projectInfo.getAsJsonPrimitive("firebase_url"); if (firebaseUrl != null) { resValues.put("firebase_database_url", firebaseUrl.getAsString()); } }
Example 14
Source File: KeyBindingsParser.java From workspacemechanic with Eclipse Public License 1.0 | 5 votes |
public KbaBindingList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { List<KbaBinding> bindingSpecList = Lists.newArrayList(); JsonArray ja = json.getAsJsonArray(); for (JsonElement jsonElement : ja) { if (jsonElement.isJsonNull()) { // This is being suppressed to support trailing commas in the list of // bindings continue; } JsonObject jo = jsonElement.getAsJsonObject(); String keySequence = jo.get(KEYS_JSON_KEY).getAsString(); String command = jo.get(COMMAND_JSON_KEY).getAsString(); JsonObject params = jo.getAsJsonObject(COMMAND_PARAMETERS_JSON_KEY); KbaBinding bindingSpec; if (params == null) { bindingSpec = new KbaBinding( keySequence, command, Maps.<String, String>newHashMap()); } else { Map<String,String> paramsAsMapOfStrings = Maps.newHashMap(); for (Entry<String, JsonElement> entry : params.entrySet()) { paramsAsMapOfStrings.put(entry.getKey(), entry.getValue().getAsString()); } bindingSpec = new KbaBinding(keySequence, command, paramsAsMapOfStrings); } bindingSpecList.add(bindingSpec); } return new KbaBindingList(bindingSpecList); }
Example 15
Source File: KcaApiData.java From kcanotify with GNU General Public License v3.0 | 5 votes |
public static JsonObject getQuestTrackInfo(String id) { JsonObject kcQuestTrackData = helper.getJsonObjectValue(DB_KEY_QUESTTRACK); if (kcQuestTrackData.has(id)) { return kcQuestTrackData.getAsJsonObject(id); } else { return null; } }
Example 16
Source File: SolrSearchProviderImpl.java From swellrt with Apache License 2.0 | 4 votes |
private static JsonArray extractDocsJson(InputStreamReader isr) { JsonObject json = new JsonParser().parse(isr).getAsJsonObject(); JsonObject responseJson = json.getAsJsonObject("response"); return responseJson.getAsJsonArray("docs"); }
Example 17
Source File: AreaDataServiceImpl.java From parker with MIT License | 4 votes |
@Override public void save() { List<String> lines = FileUtils.read("d:/test/area-data.txt"); String jsonStr = lines.get(0); JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonStr); // 省 List<AreaData> provinceList = new ArrayList<>(); JsonObject provinceJson = jsonObject.getAsJsonObject("86"); Set<String> provinceCodeSet = provinceJson.keySet(); provinceCodeSet.forEach(provinceCode -> { AreaData province = new AreaData(); province.setId(provinceCode); province.setName(provinceJson.get(provinceCode).getAsString()); province.setParent("86"); provinceList.add(province); addList(province); // 市 List<AreaData> cityList = new ArrayList<>(); JsonObject cityJson = jsonObject.getAsJsonObject(provinceCode); Set<String> cityCodeSet = cityJson.keySet(); for(String cityCode:cityCodeSet){ AreaData city = new AreaData(); city.setId(cityCode); city.setName(cityJson.get(cityCode).getAsString()); city.setParent(provinceCode); cityList.add(city); addList(city); // 区县 List<AreaData> countyList = new ArrayList<>(); JsonObject countyJson = jsonObject.getAsJsonObject(cityCode); if(countyJson == null){ continue; } Set<String> countyCodeSet = countyJson.keySet(); if(countyCodeSet == null || countyCodeSet.size() == 0){ continue; } for(String countyCode:countyCodeSet){ AreaData county = new AreaData(); county.setId(countyCode); System.out.println(countyCode); county.setName(countyJson.get(countyCode).getAsString()); county.setParent(cityCode); countyList.add(county); addList(county); // 乡镇 List<AreaData> townList = new ArrayList<>(); JsonObject townJson = jsonObject.getAsJsonObject(countyCode); if(townJson == null){ continue; } Set<String> townCodeSet = townJson.keySet(); if(townCodeSet == null || townCodeSet.size() == 0){ continue; } countyCodeSet.forEach(townCode -> { AreaData town = new AreaData(); town.setId(townCode); town.setName(townJson.get(townCode).getAsString()); town.setParent(countyCode); countyList.add(town); addList(town); }); } } }); // 清空this.areaDataList // 保存中国,最终形成一颗树 AreaData country = new AreaData(); country.setId("86"); country.setName("中国"); this.areaDataList.add(country); areaDataRepository.saveAll(this.areaDataList); }
Example 18
Source File: NamespaceInventoryCollector.java From pacbot with Apache License 2.0 | 4 votes |
public List<NamespaceVH> fetchNamespaceDetails(SubscriptionVH subscription) throws Exception { List<NamespaceVH> namespaceList = new ArrayList<NamespaceVH>(); String accessToken = azureCredentialProvider.getToken(subscription.getTenant()); String url = String.format(apiUrlTemplate, URLEncoder.encode(subscription.getSubscriptionId())); try { String response = CommonUtils.doHttpGet(url, "Bearer", accessToken); JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject(); JsonArray namespaceObjects = responseObj.getAsJsonArray("value"); if (namespaceObjects != null) { for (JsonElement namespaceElement : namespaceObjects) { NamespaceVH namespaceVH = new NamespaceVH(); JsonObject namespaceObject = namespaceElement.getAsJsonObject(); namespaceVH.setSubscription(subscription.getSubscriptionId()); namespaceVH.setSubscriptionName(subscription.getSubscriptionName()); namespaceVH.setId(namespaceObject.get("id").getAsString()); namespaceVH.setLocation(namespaceObject.get("location").getAsString()); namespaceVH.setName(namespaceObject.get("name").getAsString()); namespaceVH.setType(namespaceObject.get("type").getAsString()); JsonObject properties = namespaceObject.getAsJsonObject("properties"); JsonObject tags = namespaceObject.getAsJsonObject("tags"); JsonObject sku = namespaceObject.getAsJsonObject("sku"); if (properties != null) { HashMap<String, Object> propertiesMap = new Gson().fromJson(properties.toString(), HashMap.class); namespaceVH.setProperties(propertiesMap); } if (tags != null) { HashMap<String, Object> tagsMap = new Gson().fromJson(tags.toString(), HashMap.class); namespaceVH.setTags(tagsMap); } if (sku != null) { HashMap<String, Object> skuMap = new Gson().fromJson(sku.toString(), HashMap.class); namespaceVH.setSku(skuMap); } namespaceList.add(namespaceVH); } } } catch (Exception e) { log.error("Error collecting namespace",e); } log.info("Target Type : {} Total: {} ","Namespace",namespaceList.size()); return namespaceList; }
Example 19
Source File: FixedChatSerializer.java From Carbon-2 with GNU Lesser General Public License v3.0 | 4 votes |
@Override public IChatBaseComponent deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) throws JsonParseException { if (element.isJsonPrimitive()) { return new ChatComponentText(element.getAsString()); } else if (!element.isJsonObject()) { if (element.isJsonArray()) { JsonArray jsonArray = element.getAsJsonArray(); IChatBaseComponent chatcomp = null; for (JsonElement jsonElement : jsonArray) { IChatBaseComponent innerchatcomp = deserialize(jsonElement, jsonElement.getClass(), ctx); if (chatcomp == null) { chatcomp = innerchatcomp; } else { chatcomp.addSibling(innerchatcomp); } } return chatcomp; } else { throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component"); } } else { JsonObject jsonobject = element.getAsJsonObject(); IChatBaseComponent resultComp; if (jsonobject.has("text")) { resultComp = new ChatComponentText(jsonobject.get("text").getAsString()); } else if (jsonobject.has("translate")) { String translate = jsonobject.get("translate").getAsString(); if (jsonobject.has("with")) { JsonArray withJsonArray = jsonobject.getAsJsonArray("with"); Object[] array = new Object[withJsonArray.size()]; for (int i = 0; i < array.length; ++i) { array[i] = deserialize(withJsonArray.get(i), type, ctx); if (array[i] instanceof ChatComponentText) { ChatComponentText compText = (ChatComponentText) array[i]; if (compText.getChatModifier().g() && compText.a().isEmpty()) { array[i] = compText.g(); } } } resultComp = new ChatMessage(translate, array); } else { resultComp = new ChatMessage(translate); } } else if (jsonobject.has("score")) { JsonObject scoreJsonObject = jsonobject.getAsJsonObject("score"); if (!scoreJsonObject.has("name") || !scoreJsonObject.has("objective")) { throw new JsonParseException("A score component needs a least a name and an objective"); } resultComp = new ChatComponentScore(JsonHelper.getString(scoreJsonObject, "name"), JsonHelper.getString(scoreJsonObject, "objective")); if (scoreJsonObject.has("value")) { ((ChatComponentScore) resultComp).b(JsonHelper.getString(scoreJsonObject, "value")); } } else { if (!jsonobject.has("selector")) { throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component"); } resultComp = new ChatComponentSelector(JsonHelper.getString(jsonobject, "selector")); } if (jsonobject.has("extra")) { JsonArray entryJsonArray = jsonobject.getAsJsonArray("extra"); if (entryJsonArray.size() <= 0) { throw new JsonParseException("Unexpected empty array of components"); } for (int i = 0; i < entryJsonArray.size(); ++i) { resultComp.addSibling(deserialize(entryJsonArray.get(i), type, ctx)); } } resultComp.setChatModifier((ChatModifier) ctx.deserialize(element, ChatModifier.class)); return resultComp; } }
Example 20
Source File: SCRecommendationsCollector.java From pacbot with Apache License 2.0 | 4 votes |
private List<RecommendationVH> filterRecommendationInfo(String response,SubscriptionVH subscription){ List<RecommendationVH> recommendations = new ArrayList<>(); JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject(); JsonArray recommedationObjects = responseObj.getAsJsonArray("value"); for(JsonElement recElmnt : recommedationObjects) { JsonObject recommendObject = recElmnt.getAsJsonObject(); JsonObject properties = recommendObject.getAsJsonObject("properties"); String id = recommendObject.get("id").getAsString(); if("Active".equals(properties.get("state").getAsString())){ JsonObject secTaskParameters = properties.getAsJsonObject("securityTaskParameters"); //String baseLineName = secTaskParameters.get("baselineName")!=null?secTaskParameters.get("baselineName").getAsString():null; String policyName = secTaskParameters.get("policyName")!=null?secTaskParameters.get("policyName").getAsString():null; //String name = secTaskParameters.get("name")!=null?secTaskParameters.get("name").getAsString():null; String resourceType = secTaskParameters.get("resourceType")!=null?secTaskParameters.get("resourceType").getAsString():""; if(policyName !=null && "VirtualMachine".equals(resourceType)) { Map<String,Object> recommendationMap = new Gson().fromJson(secTaskParameters, new TypeToken<Map<String, Object>>() {}.getType() ); Object resourceId = recommendationMap.get("resourceId"); if(resourceId!=null) { RecommendationVH recommendation = new RecommendationVH(); recommendation.setSubscription(subscription.getSubscriptionId()); recommendation.setSubscriptionName(subscription.getSubscriptionName()); recommendationMap.put("resourceId",Util.removeFirstSlash(resourceId.toString())); recommendationMap.put("_resourceIdLower",Util.removeFirstSlash(resourceId.toString()).toLowerCase()); recommendation.setId(id); recommendation.setRecommendation(recommendationMap); recommendations.add(recommendation); } } } } return recommendations; }