public Optional<JsonObject> loadFileToJson(Path configPath) { if (Files.isRegularFile(configPath)) { try (Reader reader = Files.newBufferedReader(configPath, TerasologyConstants.CHARSET)) { JsonElement userConfig = new JsonParser().parse(reader); if (userConfig.isJsonObject()) { return Optional.of(userConfig.getAsJsonObject()); } } catch (IOException e) { logger.error("Failed to load config file {}, falling back on default config", configPath); } } return Optional.empty(); }
@Override public String getValue(String fieldName, JsonElement record) throws FieldMappingException { assert record.isJsonObject(); JsonObject jsonObject = record.getAsJsonObject(); if (jsonObject.has(fieldName)) { return jsonObject.get(fieldName).getAsString(); } else { throw new FieldMappingException("Could not find field :" + fieldName); } }
MaterialMetadata metadata = new MaterialMetadata(); JsonObject obj = json.getAsJsonObject(); if (obj.has("shader")) { metadata.shader = obj.getAsJsonPrimitive("shader").getAsString(); if (obj.has("params") && obj.get("params").isJsonObject()) { JsonObject params = obj.get("params").getAsJsonObject(); for (Map.Entry<String, JsonElement> prop : params.entrySet()) { if (prop.getValue().isJsonPrimitive()) { if (prop.getValue().getAsJsonPrimitive().isString()) { Optional<? extends Texture> texture = assetManager.getAsset(prop.getValue().getAsString(), Texture.class); if (texture.isPresent()) { metadata.textures.put(prop.getKey(), texture.get()); metadata.floatParams.put(prop.getKey(), prop.getValue().getAsFloat()); } else if (prop.getValue().getAsJsonPrimitive().isBoolean()) { metadata.intParams.put(prop.getKey(), (prop.getValue().getAsBoolean()) ? 1 : 0); } else if (prop.getValue().isJsonArray()) { JsonArray array = prop.getValue().getAsJsonArray(); float[] result = new float[array.size()]; boolean valid = true;
protected <T, K> Hit<T, K> extractHit(Class<T> sourceType, Class<K> explanationType, JsonElement hitElement, String sourceKey, boolean addEsMetadataFields) { Hit<T, K> hit = null; if (hitElement.isJsonObject()) { JsonObject hitObject = hitElement.getAsJsonObject(); JsonObject source = hitObject.getAsJsonObject(sourceKey); String index = hitObject.get("_index").getAsString(); String type = hitObject.get("_type").getAsString(); String id = hitObject.get("_id").getAsString(); if (hitObject.has("_score") && !hitObject.get("_score").isJsonNull()) { score = hitObject.get("_score").getAsDouble(); String routing = null; if (hitObject.has("_parent") && !hitObject.get("_parent").isJsonNull()) { parent = hitObject.get("_parent").getAsString(); if (hitObject.has("_routing") && !hitObject.get("_routing").isJsonNull()) { routing = hitObject.get("_routing").getAsString(); if (hitObject.has("matched_queries") && !hitObject.get("matched_queries").isJsonNull()) { JsonArray rawMatchedQueries = hitObject.get("matched_queries").getAsJsonArray(); rawMatchedQueries.forEach(matchedQuery -> { matchedQueries.add(matchedQuery.getAsString());
@Override public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) { return new UILabel(json.getAsString()); JsonObject jsonObject = json.getAsJsonObject(); String type = jsonObject.get(TYPE_FIELD).getAsString(); ClassMetadata<? extends UIWidget, ?> elementMetadata = nuiManager.getWidgetMetadataLibrary().resolve(type, ModuleContext.getContext()); if (elementMetadata == null) { if (jsonObject.has(ID_FIELD)) { id = jsonObject.get(ID_FIELD).getAsString(); if (jsonObject.has(field.getSerializationName())) { unknownFields.remove(field.getSerializationName()); if (field.getName().equals(CONTENTS_FIELD) && UILayout.class.isAssignableFrom(elementMetadata.getType())) { field.setValue(element, context.deserialize(jsonObject.get(field.getSerializationName()), field.getType())); if (jsonObject.has(CONTENTS_FIELD)) { for (JsonElement child : jsonObject.getAsJsonArray(CONTENTS_FIELD)) { UIWidget childElement = context.deserialize(child, UIWidget.class); if (childElement != null) { LayoutHint hint = null; if (child.isJsonObject()) { JsonObject childObject = child.getAsJsonObject(); if (layoutHintType != null && !layoutHintType.isInterface() && !Modifier.isAbstract(layoutHintType.getModifiers()) && childObject.has(LAYOUT_INFO_FIELD)) {
if (jsonElement == null || !jsonElement.isJsonObject()) { return retrievedRevisions; JsonObject jsonObj = jsonElement.getAsJsonObject(); if (jsonObj == null || !jsonObj.has(JSON_MEMBER_QUERY)) { return retrievedRevisions; if (!queryObj.has(JSON_MEMBER_PAGES)) { return retrievedRevisions; if (pagesObj.entrySet().isEmpty()) { return retrievedRevisions; JsonObject pageIdObj = pagesObj.getAsJsonObject(pagesObj.entrySet().iterator().next().getKey()); if (!pageIdObj.has(JSON_MEMBER_REVISIONS)) { return retrievedRevisions; JsonObject revObj = revElement.getAsJsonObject(); if (pageIdObj.has(JSON_MEMBER_PAGEID)) { revObj.add(JSON_MEMBER_PAGEID, pageIdObj.get(JSON_MEMBER_PAGEID)); if (pageIdObj.has(JSON_MEMBER_TITLE)) { revObj.add(JSON_MEMBER_TITLE, pageIdObj.get(JSON_MEMBER_TITLE));
@Override public JsonElement mergeInto(final JsonElement input, final JsonElement key, final JsonElement value) { final JsonObject output; if (input.isJsonNull()) { output = new JsonObject(); } else if (input.isJsonObject()) { output = new JsonObject(); input.getAsJsonObject().entrySet().forEach(entry -> output.add(entry.getKey(), entry.getValue())); } else { return input; } output.add(key.getAsString(), value); return output; }
@Override public JsonElement remove(final JsonElement input, final String key) { if (input.isJsonObject()) { final JsonObject result = new JsonObject(); input.getAsJsonObject().entrySet().stream().filter(entry -> !Objects.equals(entry.getKey(), key)).forEach(entry -> result.add(entry.getKey(), entry.getValue())); return result; } return input; }
@Override public DataPoint getDataPoint(long timestamp, JsonElement json) throws IOException { if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); double real = object.get("real").getAsDouble(); double imaginary = object.get("imaginary").getAsDouble(); return new ComplexDataPoint(timestamp, real, imaginary); } else throw new IOException("JSON object is not a valid complex data point"); }
String jsonStr = "your json string "; Gson gson = new Gson(); JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject(); JsonElement elem = jsonObj.get("msg"); if(elem.isJsonArray()) { //**Array** ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType()); } else if(elem.isJsonObject()) { //**Object** Note note = gson.fromJson(elem.toString(), MyMessage.class); } else { //**String** String note = elem.toString(); }
Class<?> valueClass; if (jsonElement.isJsonObject()) { JsonElement typeNameJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD_NAME); String typeName = typeNameJsonElement.getAsString();
public static boolean isNotNullOrEmpty(ValidationErrors validationErrors, Object name, JsonElement value) { if (value == null) { validationErrors.addErrorMessage(name + " may not be null."); return false; } if (value.isJsonNull()) { validationErrors.addErrorMessage(name + " may not be empty."); return false; } if (value.isJsonArray() && value.getAsJsonArray().size() < 1) { validationErrors.addErrorMessage(name + " may not be an empty array."); return false; } if (!value.isJsonObject() && value.getAsString().isEmpty()) { validationErrors.addErrorMessage(name + " may not be empty."); return false; } return true; }
@Override public EntityData.GlobalStore deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { EntityData.GlobalStore.Builder world = EntityData.GlobalStore.newBuilder(); if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); JsonArray prefabArray = jsonObject.getAsJsonArray("prefab"); if (prefabArray != null) { for (JsonElement prefabElem : prefabArray) { world.addPrefab((EntityData.Prefab) context.deserialize(prefabElem, EntityData.Prefab.class)); } } JsonArray entityArray = jsonObject.getAsJsonArray("entity"); if (entityArray != null) { for (JsonElement entityElem : entityArray) { world.addEntity((EntityData.Entity) context.deserialize(entityElem, EntityData.Entity.class)); } } JsonPrimitive nextId = jsonObject.getAsJsonPrimitive("next_entity_id"); if (nextId != null) { world.setNextEntityId(nextId.getAsInt()); } } return world.build(); } }
@Override public EntityData.Value deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { EntityData.Value.Builder value = EntityData.Value.newBuilder(); if (json.isJsonPrimitive()) { extractPrimitive(value, json); } else if (json.isJsonObject()) { extractMap(json, context, value); } else if (json.isJsonArray()) { JsonArray jsonArray = json.getAsJsonArray(); TByteList byteList = new TByteArrayList(); for (JsonElement element : jsonArray) { if (element.isJsonArray()) { value.addValue((EntityData.Value) context.deserialize(element, EntityData.Value.class)); } else if (element.isJsonObject()) { value.addValue((EntityData.Value) context.deserialize(element, EntityData.Value.class)); } else if (element.isJsonPrimitive()) { extractPrimitive(value, element); if (element.getAsJsonPrimitive().isNumber()) { try { byteList.add(element.getAsByte()); } catch (NumberFormatException nfe) { byteList.add((byte) 0); } } } } value.setBytes(ByteString.copyFrom(byteList.toArray())); } return value.build(); }
out.beginObject(); for (Map.Entry<K, V> entry : map.entrySet()) { out.name(String.valueOf(entry.getKey())); valueTypeAdapter.write(out, entry.getValue()); JsonElement keyElement = keyTypeAdapter.toJsonTree(entry.getKey()); keys.add(keyElement); values.add(entry.getValue()); hasComplexKeys |= keyElement.isJsonArray() || keyElement.isJsonObject();
private void parseBuckets(JsonElement buckets) { if (buckets.isJsonArray()) { int elementNumber = 0; for (JsonElement bucket : buckets.getAsJsonArray()) { addBucket("filter" + Integer.toString(elementNumber++), bucket.getAsJsonObject()); } } else if (buckets.isJsonObject()) { for (Map.Entry<String, JsonElement> bucket : buckets.getAsJsonObject().entrySet()) { addBucket(bucket.getKey(), bucket.getValue().getAsJsonObject()); } } else { log.debug("Skipped bucket parsing because Buckets element of JSON was neither Object nor Array."); } }
private int findIndex(JsonObject node) { int index = -1; JsonObject parent = node.getAsJsonObject("parent"); for (Map.Entry<String, JsonElement> entry : parent.entrySet()) { if (entry.getValue().isJsonArray() && !entry.getKey().equals(FormattingConstants.WS)) { for (int i = 0; i < entry.getValue().getAsJsonArray().size(); i++) { JsonElement element = entry.getValue().getAsJsonArray().get(i); if (element.isJsonObject() && element.getAsJsonObject().has("id") && element.getAsJsonObject().get("id").getAsString() .equals(node.get("id").getAsString())) { index = i; } } } } return index; }
@Override public Map<String, String> deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { if (!arg0.isJsonObject()) { throw new JsonParseException(arg0.toString() + " is not Json Object, cannot convert to map"); } JsonObject objs = arg0.getAsJsonObject(); Map<String, String> map = new HashMap<String, String>(); for (Entry<String, JsonElement> e : objs.entrySet()) { if (!e.getValue().isJsonPrimitive()) { throw new JsonParseException(e.getValue().toString() + " is not a Json primitive," + arg0 + " can not convert to map"); } map.put(e.getKey(), e.getValue().getAsString()); } return map; }
/** * @param claimRequestString * @return */ private JsonObject parseClaimRequest(String claimRequestString) { if (Strings.isNullOrEmpty(claimRequestString)) { return null; } else { JsonElement el = parser.parse(claimRequestString); if (el != null && el.isJsonObject()) { return el.getAsJsonObject(); } else { return null; } } }
@Override public Optional<Map<JsonElement, JsonElement>> getMapValues(final JsonElement input) { if (input.isJsonObject()) { return Optional.of(input.getAsJsonObject().entrySet().stream().map(entry -> Pair.of(new JsonPrimitive(entry.getKey()), entry.getValue())).collect(Collectors.toMap(Pair::getFirst, Pair::getSecond))); } return Optional.empty(); }