[英]How Parse JSON using GSON WHen object is either JSONObject or JSONArray
[英]Can't parse some JSON into a JsonArray using GSON
我正在尝试从JSON响应中获取值。 除了从以下字符串中提取数组之外,我已完成所有工作:
{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
我知道GSON正在尝试解析它,因为出现此错误:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
我正在使用以下代码尝试对其进行解析:
final JsonElement midElement = obj.get("mid");
final JsonArray midArray = midElement.getAsJsonArray();
for(Object rate : midArray){
final JsonObject rateObj = (JsonObject)rate;
final JsonElement openElement = rateObj.get("o");
open = openElement.getAsFloat();
final JsonElement highElement = rateObj.get("h");
high = highElement.getAsFloat();
final JsonElement lowElement = rateObj.get("l");
low = lowElement.getAsFloat();
final JsonElement closeElement = rateObj.get("c");
close = closeElement.getAsFloat();
}
首先,它看起来不像是有效的JSON数组。 它应该看起来像这样
[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}]
尝试使用以下代码将其解析为JSON格式。
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("mid");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("o");
}
然后将其转换为您首选的数据形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.