[英]Parsing Nested JSON array to an Array using GSON
I need to parse the following Json 我需要解析以下Json
[
"foo",
[
"foot mercato",
"football",
"foot center",
"foorzik",
"footao"
]
]
in java using Gson . 在Java中使用Gson 。
Im really interested in values in the Array: so far I have tried: 我真的很喜欢Array中的值:到目前为止,我已经尝试过:
String jsonStr = "[" + "\"foo\"," + " [" + " \"foot mercato\"," + " \"football\"," + " \"foot center\"," +
" \"foorzik\"," + " \"footao\"" + " ]" + "]";
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(jsonStr).getAsJsonArray();
any suggestion? 有什么建议吗?
Once you get your array, you can iterate through all the elements of it. 获得数组后,就可以遍历数组的所有元素。
for(JsonElement e : array) {
System.out.println(e);
}
which will output 将输出
"foo"
["foot mercato","football","foot center","foorzik","footao"]
If you only want the values in the nested array, you can do: 如果只需要嵌套数组中的值,则可以执行以下操作:
JsonArray nestedArray = parser.parse(jsonStr).getAsJsonArray().get(1).getAsJsonArray();
for(JsonElement e : nestedArray) {
System.out.println(e);
}
which will output 将输出
"foot mercato"
"football"
"foot center"
"foorzik"
"footao"
This may help: 这可能会有所帮助:
String jsonStr = "[" + "\"foo\"," + " [" + " \"foot mercato\"," + " \"football\"," + " \"foot center\","
+ " \"foorzik\"," + " \"footao\"" + " ]" + "]";
Gson gson = new Gson();
ArrayList<Object> dest = new ArrayList<Object>();
dest = gson.fromJson(jsonStr, dest.getClass());
for (Object e : dest) {
System.out.println("T:" + e.getClass().getCanonicalName());
if (e instanceof String) {
System.out.println(e);
} else if (e instanceof ArrayList) {
for (String ele : (ArrayList<String>) e) {
System.out.println(ele);
}
}
}
Will generate: 将产生:
T:java.lang.String T:java.lang.String中
foo FOO
T:java.util.ArrayList T:java.util.ArrayList中
foot mercato 脚Mercato
football 足球
foot center 脚中心
foorzik foorzik
footao footao
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.