I have problems accessing data in a JSON string. What am I doing wrong?
Working:
JSONObject obj = new JSONObject("JSON-STRING");
JSONArray arr = obj.getJSONArray("weather");
System.out.println(arr.getJSONObject(0).get("description"); >> clear sky
Not working:
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)
The JSON-String:
{
"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
}
{..}represents object,[..]represents array. As you see"main": {...}holds an object not an array, which is whygetJSONArray("main")is causing problems.