[英]Can't parse some JSON into a JsonArray using GSON
I am trying to get the values from a JSON response. 我正在尝试从JSON响应中获取值。 I got everything to work, except extracting an array from the following string:
除了从以下字符串中提取数组之外,我已完成所有工作:
{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I know GSON is trying to parse it because I get this error: 我知道GSON正在尝试解析它,因为出现此错误:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I am using the following code to attempt to parse it: 我正在使用以下代码尝试对其进行解析:
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();
}
First of all it doesn't look like a valid JSON array. 首先,它看起来不像是有效的JSON数组。 It should look like this
它应该看起来像这样
[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}]
Try this following code to parse it in JSON format. 尝试使用以下代码将其解析为JSON格式。
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("mid");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("o");
}
Then convert it your preferred data form. 然后将其转换为您首选的数据形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.