繁体   English   中英

有没有一种方法可以在不创建POJO的情况下将复杂的JSON转换为对象?

[英]Is there a way to convert a complex JSON to an object without creating a POJO?

我想将JSON-String转换为对象。 通常,我创建一个POJO并将String转换为GSONJSONObject转换为POJO。 但是,我不必创建POJO会有更好的选择吗?

目的是获得一个对象,在这里我可以以任何方式访问JSON的键和值...,例如jsonObject.getKey(“ foo”)。getProperty(“ bar”)..或任何:D

大多数JSON解析器/生成器库都有每种JSON类型的类型

Gson具有JsonElement及其子类型。 这是一个可以链接呼叫的示例。

public static void main(String[] args) throws Exception {
    String jsonString = "{\"property1\":\"someValue\", \"arrayProperty\":[{\"first\":1234, \"second\":-13.123}, {\"nested\":\"so deep\"}], \"finally\":\"last\"}";
    Gson gson = new Gson();
    JsonElement element = gson.fromJson(jsonString, JsonElement.class);
    System.out.println(element);
    JsonObject jsonObject = element.getAsJsonObject(); // should test type before you do this

    System.out.println(jsonObject.get("arrayProperty").getAsJsonArray().get(0));
}

版画

{"property1":"someValue","arrayProperty":[{"first":1234,"second":-13.123},{"nested":"so deep"}],"finally":"last"}
{"first":1234,"second":-13.123}

上面的内容或多或少通过JsonObjectLinkedTreeMapJsonArrayList实现。 它提供了包装器来访问更多JsonObjectJsonArrayJsonNull和/或JsonPrimitive实例的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM