我在访问 JSON 字符串中的数据时遇到问题。我做错了什么?
工作:
JSONObject obj = new JSONObject("JSON-STRING");
JSONArray arr = obj.getJSONArray("weather");
System.out.println(arr.getJSONObject(0).get("description"); >> clear sky
不工作:
JSONObject obj = new JSONObject("JSON-STRING");
JSONArray arr = obj.getJSONArray("main");
System.out.println(arr.getJSONObject(0).get("temp"); >> 285.15
异常(exception):
org.json.JSONException: JSONObject["main"] is not a JSONArray. at org.json.JSONObject.getJSONArray(JSONObject.java:622) at main.SmartHomeBot.onUpdateReceived(SmartHomeBot.java:47) at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:274)
JSON 字符串:
{
"coord": {
"lon": 6.55,
"lat": 51.27
},
"weather": [{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 285.15,
"pressure": 1034,
"humidity": 30,
"temp_min": 285.15,
"temp_max": 285.15
},
"visibility": 10000,
"wind": {
"speed": 2.6
},
"clouds": {
"all": 0
},
"dt": 1492705200,
"sys": {
"type": 1,
"id": 4909,
"message": 0.2825,
"country": "DE",
"sunrise": 1492662386,
"sunset": 1492713582
},
"id": 2808559,
"name": "Willich",
"cod": 200
}
最佳答案
您会收到错误消息,因为 weather
是多个 weather
的数组,而 main
是单个对象。
两者的区别如下图所示:
"weather": [{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
和
"main": {
"temp": 285.15,
"pressure": 1034,
"humidity": 30,
"temp_min": 285.15,
"temp_max": 285.15
},
所以在 JSON "weather": [{....}, {....}, {....}]
[]
中显示weather
就是数组。
关于Java 访问 JSON 字符串中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43526655/