Reputation: 1911
I want to convert a JSON-String to an object. Normally I create an POJO and convert the String to a GSON
or JSONObject
to my POJO. But is there a better where I don't have to create an POJO?
The goal is to get an object where I can access the keys and values of the JSON... in whatever way, like jsonObject.getKey("foo").getProperty("bar").. or whatever :D
Upvotes: 1
Views: 545
Reputation: 280132
Most JSON parser/generator libraries have a type for each of the JSON types.
Gson has JsonElement
and its sub types. Here's an example where you can chain calls.
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));
}
prints
{"property1":"someValue","arrayProperty":[{"first":1234,"second":-13.123},{"nested":"so deep"}],"finally":"last"}
{"first":1234,"second":-13.123}
The above is more or less implemented with a LinkedTreeMap
for JsonObject
and a List
for JsonArray
. It provides wrappers to access the elements as more JsonObject
, JsonArray
, JsonNull
, and/or JsonPrimitive
instances.
Upvotes: 2