我正在尝试从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();
}
答案 0 :(得分:5)
首先,它看起来不像一个有效的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");
}
然后将其转换为您首选的数据表单。