本文整理了Java中com.google.gson.JsonElement.getAsJsonObject()
方法的一些代码示例,展示了JsonElement.getAsJsonObject()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonElement.getAsJsonObject()
方法的具体详情如下:
包路径:com.google.gson.JsonElement
类名称:JsonElement
方法名:getAsJsonObject
[英]convenience method to get this element as a JsonObject. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling #isJsonObject()first.
[中]将此元素作为JsonObject获取的方便方法。如果该元素属于其他类型,则会导致IllegalStateException。因此,最好先调用#isJsonObject()以确保此元素为所需类型,然后再使用此方法。
代码示例来源:origin: stackoverflow.com
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
代码示例来源:origin: Vedenin/useful-java-links
/**
* Example to readJson using TreeModel
*/
private static void readJson() throws IOException {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}");
JsonObject rootObject = jsonElement.getAsJsonObject();
String message = rootObject.get("message").getAsString(); // get property "message"
JsonObject childObject = rootObject.getAsJsonObject("place"); // get place object
String place = childObject.get("name").getAsString(); // get property "name"
System.out.println(message + " " + place); // print "Hi World!"*/
}
代码示例来源:origin: MovingBlocks/Terasology
public JsonObject loadDefaultToJson() {
try (Reader baseReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/default.cfg")))) {
return new JsonParser().parse(baseReader).getAsJsonObject();
} catch (IOException e) {
throw new RuntimeException("Missing default configuration file");
}
}
代码示例来源:origin: gocd/gocd
@Override
public Filters deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject j = json.getAsJsonObject();
final JsonElement filters = j.get(KEY_FILTERS);
if (null == filters) {
throw new JsonParseException("Missing filters array!");
}
final ArrayList<DashboardFilter> viewFilters = new ArrayList<>();
filters.getAsJsonArray().forEach((f) -> viewFilters.add(context.deserialize(f, DashboardFilter.class)));
return new Filters(viewFilters);
}
}
代码示例来源:origin: chanjarster/weixin-java-tools
@Override
public String tagCreate(String tagName) throws WxErrorException {
String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/create";
JsonObject o = new JsonObject();
o.addProperty("tagname", tagName);
String responseContent = post(url, o.toString());
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return tmpJsonElement.getAsJsonObject().get("tagid").getAsString();
}
代码示例来源:origin: searchbox-io/Jest
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());
代码示例来源:origin: apache/incubator-gobblin
private static Set<SourceEntity> getSourceEntities(String response) {
Set<SourceEntity> result = Sets.newHashSet();
JsonObject jsonObject = new Gson().fromJson(response, JsonObject.class).getAsJsonObject();
JsonArray array = jsonObject.getAsJsonArray("sobjects");
for (JsonElement element : array) {
String sourceEntityName = element.getAsJsonObject().get("name").getAsString();
result.add(SourceEntity.fromSourceEntityName(sourceEntityName));
}
return result;
}
代码示例来源:origin: MovingBlocks/Terasology
@Override
public EntityData.Entity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
EntityData.Entity.Builder entity = EntityData.Entity.newBuilder();
JsonObject jsonObject = json.getAsJsonObject();
case "parentprefab":
if (entry.getValue().isJsonPrimitive()) {
entity.setParentPrefab(entry.getValue().getAsString());
case "removedcomponent":
if (entry.getValue().isJsonArray()) {
for (JsonElement element : entry.getValue().getAsJsonArray()) {
entity.addRemovedComponent(element.getAsString());
代码示例来源:origin: MovingBlocks/Terasology
private static void merge(JsonObject target, JsonObject from) {
for (Map.Entry<String, JsonElement> entry : from.entrySet()) {
if (entry.getValue().isJsonObject()) {
if (target.has(entry.getKey()) && target.get(entry.getKey()).isJsonObject()) {
merge(target.get(entry.getKey()).getAsJsonObject(), entry.getValue().getAsJsonObject());
} else {
target.remove(entry.getKey());
target.add(entry.getKey(), entry.getValue());
}
} else {
target.remove(entry.getKey());
target.add(entry.getKey(), entry.getValue());
}
}
}
代码示例来源:origin: apache/incubator-gobblin
/**
* Get the expected high {@link Watermark} as a {@link JsonElement}.
*
* @return a {@link JsonElement} representing the expected high {@link Watermark}.
*/
public JsonElement getExpectedHighWatermark() {
return JSON_PARSER.parse(getProp(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY)).getAsJsonObject()
.get(WatermarkInterval.EXPECTED_HIGH_WATERMARK_TO_JSON_KEY);
}
代码示例来源:origin: MovingBlocks/Terasology
@Override
public BlockShapeData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
BlockShapeData shape = new BlockShapeData();
JsonObject shapeObj = json.getAsJsonObject();
if (shapeObj.has(DISPLAY_NAME)) {
shape.setDisplayName(shapeObj.getAsJsonPrimitive(DISPLAY_NAME).getAsString());
}
for (BlockPart part : BlockPart.values()) {
if (shapeObj.has(part.toString().toLowerCase(Locale.ENGLISH))) {
JsonObject meshObj = shapeObj.getAsJsonObject(part.toString().toLowerCase(Locale.ENGLISH));
shape.setMeshPart(part, (BlockMeshPart) context.deserialize(meshObj, BlockMeshPart.class));
if (part.isSide() && meshObj.has(FULL_SIDE)) {
shape.setBlockingSide(part.getSide(), meshObj.get(FULL_SIDE).getAsBoolean());
}
}
}
if (shapeObj.has(COLLISION) && shapeObj.get(COLLISION).isJsonObject()) {
JsonObject collisionInfo = shapeObj.get(COLLISION).getAsJsonObject();
processCollision(context, shape, collisionInfo);
} else {
shape.setCollisionShape(COLLISION_SHAPE_FACTORY.getNewUnitCube());
shape.setCollisionSymmetric(true);
}
return shape;
}
代码示例来源:origin: gocd/gocd
public <T> T determineJsonElementForDistinguishingImplementers(JsonElement json, JsonDeserializationContext context, String field, String origin) {
JsonObject jsonObject = json.getAsJsonObject();
JsonPrimitive prim = (JsonPrimitive) jsonObject.get(field);
JsonPrimitive originField = (JsonPrimitive) jsonObject.get(origin);
String typeName = prim.getAsString();
Class<?> klass = classForName(typeName, originField == null ? "gocd" : originField.getAsString());
return context.deserialize(jsonObject, klass);
}
代码示例来源:origin: apache/zeppelin
@Override public R read(JsonReader in) throws IOException {
JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
String label = (labelJsonElement == null ? null : labelJsonElement.getAsString());
@SuppressWarnings("unchecked") // registration requires that subtype extends T
TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
if (delegate == null) {
throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
+ label + "; did you forget to register a subtype?");
}
return delegate.fromJsonTree(jsonElement);
}
代码示例来源:origin: konsoletyper/teavm
private void readCountries(String localeCode, CLDRLocale locale, InputStream input) {
JsonObject root = (JsonObject) new JsonParser().parse(new InputStreamReader(input));
JsonObject countriesJson = root.get("main").getAsJsonObject().get(localeCode).getAsJsonObject()
.get("localeDisplayNames").getAsJsonObject().get("territories").getAsJsonObject();
for (Map.Entry<String, JsonElement> property : countriesJson.entrySet()) {
String country = property.getKey();
if (availableCountries.contains(country)) {
locale.territories.put(country, property.getValue().getAsString());
}
}
}
代码示例来源:origin: aa112901/remusic
public static MusicDetailInfo getInfo(final String id) {
MusicDetailInfo info = null;
try {
JsonObject jsonObject = HttpUtil.getResposeJsonObject(BMA.Song.songBaseInfo(id).trim()).get("result")
.getAsJsonObject().get("items").getAsJsonArray().get(0).getAsJsonObject();
info = MainApplication.gsonInstance().fromJson(jsonObject, MusicDetailInfo.class);
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
代码示例来源:origin: MovingBlocks/Terasology
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();
}
代码示例来源:origin: chanjarster/weixin-java-tools
public String shortUrl(String long_url) throws WxErrorException {
String url = "https://api.weixin.qq.com/cgi-bin/shorturl";
JsonObject o = new JsonObject();
o.addProperty("action", "long2short");
o.addProperty("long_url", long_url);
String responseContent = execute(new SimplePostRequestExecutor(), url, o.toString());
JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
return tmpJsonElement.getAsJsonObject().get("short_url").getAsString();
}
代码示例来源:origin: MovingBlocks/Terasology
@Override
public EntityData.Prefab deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
EntityData.Prefab.Builder prefab = EntityData.Prefab.newBuilder();
JsonObject jsonObject = json.getAsJsonObject();
case "name":
if (entry.getValue().isJsonPrimitive()) {
prefab.setName(entry.getValue().getAsString());
prefab.setParentName(entry.getValue().getAsString());
prefab.addRemovedComponent(entry.getValue().getAsString());
} else if (entry.getValue().isJsonArray()) {
for (JsonElement element : entry.getValue().getAsJsonArray()) {
prefab.addRemovedComponent(element.getAsString());
代码示例来源:origin: searchbox-io/Jest
private void parseBuckets(JsonArray buckets) {
//todo support keyed:true as well
for (JsonElement bucketv : buckets) {
JsonObject bucket = bucketv.getAsJsonObject();
Range geoDistance = new Range(
bucket,
bucket.has(String.valueOf(FROM)) ? bucket.get(String.valueOf(FROM)).getAsDouble() : null,
bucket.has(String.valueOf(TO)) ? bucket.get(String.valueOf(TO)).getAsDouble() : null,
bucket.has(String.valueOf(DOC_COUNT)) ? bucket.get(String.valueOf(DOC_COUNT)).getAsLong() : null);
geoDistances.add(geoDistance);
}
}
代码示例来源:origin: apache/incubator-gobblin
/**
* Get the low {@link Watermark} as a {@link JsonElement}.
*
* @return a {@link JsonElement} representing the low {@link Watermark} or
* {@code null} if the low {@link Watermark} is not set.
*/
public JsonElement getLowWatermark() {
if (!contains(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY)) {
return null;
}
return JSON_PARSER.parse(getProp(ConfigurationKeys.WATERMARK_INTERVAL_VALUE_KEY)).getAsJsonObject()
.get(WatermarkInterval.LOW_WATERMARK_TO_JSON_KEY);
}
内容来源于网络,如有侵权,请联系作者删除!