我为此使用gson-2.5。这两个json的格式略有不同,第一个是json;
"usethis": [
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
我本可以对此进行解析,以便以这种方式获取“文本”,并且一切都会好起来的。
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(listcontents);
JsonObject rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("usethis").getAsJsonArray();
for(int i = 0; i < items.size(); i++) {
JsonObject item = items.get(i).getAsJsonObject();
String thetext = item.get("text").getAsString();
System.out.println("text: " + thetext + "\n");
}
不同之处在于,在第二个中,与第一个中使用“ usethis”的根对象不同,我没有任何东西可以作为根对象。
[
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
和设置
rootobj.get("usethis").getAsJsonArray();
到
rootobj.get("").getAsJsonArray();
只是给我一个错误。我将如何解析第二个json?
JsonElement只是JsonArray和JsonObject的超类。
JsonArray items = root.getAsJsonArray();
应该做你想做的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句