我需要从Java中的JSON文件中读取股票价值
{"name":"UCG.MI", "history":
{"2019-05-16":{"op":"1","cl":"2","h":"2","lo":"1","vol":"10"},
"2019-05-15":{"op":"1","cl":"2","h":"2","lo":"1","vol":"10"},
"2019-05-14":{"op":"1","cl":"2","h":"2","lo":"1","vol":"10"},
"2019-05-13":{"op":"1","cl":"2","h":"2","lo":"1","vol":"10"},
"2000-01-04":{"op":"1","cl":"2","h":"2","lo":"1","vol":"10"},
"2000-01-03":{"op":"1","cl":"2","h":"2","lo":"1","vol":"10"}
}
}
我可以使用org.json来获取“名称”
json = new String(Files.readAllBytes(Paths.get("UCG.json")), "UTF-8");
JSONObject obj = new JSONObject(json);
String pageName = obj.getString("name");
System.out.println(pageName);
有人可以帮助我阅读文件的其余部分吗?
我尝试
JSONArray arr = obj.getJSONArray("history");
for (int i = 0; i < arr.length(); i++) {
String post_id = arr.getJSONObject(i).getString("op");
}
但是我会犯错误
org.json.JSONException:JSONObject [“ history”]不是JSONArray。
预先感谢
答案 0 :(得分:0)
您会收到错误消息,因为JSON中的history
属性不是数组而是对象。请尝试以下部分,而不是已有的
JSONObject history = obj.getJSONObject("history");
for (String date: history.keySet()) {
JSONObject post = history.getJSONObject(date);
String postId = post.getString("op");
// ...
}
答案 1 :(得分:0)
首先,历史记录是一个JSON对象。其次,“历史记录”包含一个具有六个Key(String)-Value(JSONObject)对的对象。
上面的逻辑在这里实现。
JSONObject history = (JSONObject) jsonObject.get("history");
Set<String> dates = history.keySet();
for(String date:dates)
{
JSONObject details = (JSONObject) history.get(date);
System.out.println(details.get("op"));
}
注意:我在这里使用了json-simple java库。