[英]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, 我最近才刚开始进行android开发,并且想出了一个看起来像这样的json,
"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. 我正在使用Gson
解析json。 How should i approach to create a model class for this json? 我应该如何为这个json创建模型类? Any help would be appreciated!! 任何帮助,将不胜感激!!
First of all, this JSON string looks invalid. 首先,此JSON字符串看起来无效。 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: 如果您更正了这些问题,则可以使用GSON进行解析,如下所示:
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. 显然,除了打印之外,您还可以使用这些解析后的值进行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.