Esixt Esixt - 1 year ago 197
JSON Question

Deserialize nested JSON array in Java with Gson

Something like this. says it is valid. Json inside {} simplified for this example.


Or with indents:

[0, {
"ok": true
[1, {
"ok": false

This is class for object JSONClass.

public class JSONClass {
boolean ok;

If I got it right, this JSON string is array of arrays, latter containing some ID, actual JSON data and empty array. How could I deserialize that?

This doesn't work. I also tried making class with subclasses, didn't work out.

JSONClass[] t = g.fromJson(json, JSONClass[].class);

Answer Source

Well, you have an array of arrays here. Gson will let you convert the JSON objects themselves into the class you want - but you'll have to call gson.fromJson() on each of them separately.

Given String json containing your json, something like this should work:

Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = jsonParser.parse(json).getAsJsonArray();

for (JsonElement e: jsonArray) {
    JSONClass o = gson.fromJson(e.getAsJsonArray().get(1), JSONClass.class);

Essentially, the JsonParser will convert your text into a JsonElement, which is the Gson base class for Json arrays and objects. We can iterate over the elements of the JsonArray which we parsed our text into, which in turn is another array of the format [id, object] - and for each element, take the object portion, and deserialize that into a POJO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download