简体   繁体   中英

Parsing a JSONArray inside a keyless JSONArray using Gson

I had just started doing android development recently and I have come up with a json that looks like this,

"rows": [

    [ 
        { "val": "abc", 
          "val1":"cde" 
        },

        { "val": "efg", 
          "val1":"hij" 
        },
    ],

    [ 
        { "val": "klm", 
          "val1":"nop" 
        },

        { "val": "qrs", 
          "val1":"tuv" 
        },
    ],
    ........
    ........
    ........
]

Now as you can see the outer array has no keys but the inner ones do. I am using Gson for parsing the json. How should i approach to create a model class for this json? Any help would be appreciated!!

First of all, this JSON string looks invalid. There shouldn't be a comma after the second element of every two-element inner array. And wrap the whole thing in {} brackets. Like this:

{"rows": [
    [ 
        { "val": "abc", 
          "val1":"cde" 
        },
        { "val": "efg", 
          "val1":"hij" 
        }
    ],
    [ 
        { "val": "klm", 
          "val1":"nop" 
        },
        { "val": "qrs", 
          "val1":"tuv" 
        }
    ]
]}

If you correct those, you can parse it with GSON like this:

    JsonElement root = new JsonParser().parse(jstring);
    root.getAsJsonObject().get("rows")
        .getAsJsonArray().forEach(innerArray -> {
            innerArray.getAsJsonArray().forEach(element -> {
                System.out.println("val equals "+element.getAsJsonObject().get("val"));
                System.out.println("val1 equals "+element.getAsJsonObject().get("val1"));
            });
    });

Obviously, instead of printing you can do whatever you like with those parsed values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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