Can't figure out how to parse the following JSON string with GSON into any proper object to retrieve its data. The string is:
无法弄清楚如何使用GSON将以下JSON字符串解析为任何适当的对象以检索其数据。字符串是:
{"Values":[{"Date":"2014-10-01","Value":386788.0},{"Date":"2014-11-01","Value":429131.0},{"Date":"2014-12-01","Value":215217.0},{"Date":"2015-01-01","Value":270422.0},{"Date":"2015-02-01","Value":261412.0},{"Date":"2015-03-01","Value":354668.0}]}
I figured out that square brackets mean that it's an ArrayList, but then there's another object inside.
我发现方括号意味着它是一个ArrayList,但后面还有另一个对象。
If I try and try to iterare over the ArrayList:
如果我尝试迭代ArrayList:
Map<String,ArrayList<String>> map = gson.fromJson(json, Map.class);
Then it complains about:
然后它抱怨:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.lang.String
And if I try the opposite:
如果我尝试相反:
Map<String,LinkedTreeMap<String,String>> map = gson.fromJson(json, Map.class);
Then it's also complaining about it:
然后它也抱怨它:
java.util.ArrayList cannot be cast to com.google.gson.internal.LinkedTreeMap
Don't understand that format :-/
不明白那种格式: - /
Thanks for any advice!
谢谢你的建议!
1 个解决方案
#1
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse(yourString);
for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
JsonArray array = entry.getValue().getAsJsonArray();
for (JsonElement elementJSON : array) {
[...]
}
}
#1
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject)parser.parse(yourString);
for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
JsonArray array = entry.getValue().getAsJsonArray();
for (JsonElement elementJSON : array) {
[...]
}
}