2017-04-20 37 views
1

我在訪問JSON字符串中的數據時遇到問題。我究竟做錯了什麼?JSON字符串中的Java訪問數據

工作:

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 

例外:

​​

的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 
} 
+3

數據'{..}'代表對象,'[..]'代表陣列。正如你看到的「main」:{...}'不包含數組,這就是爲什麼getJSONArray(「main」)引起問題的原因。 – Pshemo

+0

投票結束爲排印錯誤。這裏沒有更多解釋。 – Pshemo

+0

JSONObject obj = new JSONObject(JSON-STRING); \t \t JSONObject arr = obj.getJSONObject(「main」); \t \t \t \t System.out.println(arr.get(「temp」));爲我修好了。謝謝! – piguy

回答

1

您得到的錯誤,因爲weather是多個weathermain是單個對象的數組。二者之間

差異如下所示:

"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是數組。

0

在您的父級json鍵值「weather」中表示JSONArray,但鍵值「main」表示JSONObject而不是JSONArray。

要提取的JSONObject你應該做象下面

JSONObject mainObj = obj.getJSONObject("main"); 
System.out.println(mainObj.get("temp")); 
0
String jsonobj = "{\n \"coord\": {\n  \"lon\": 6.55,\n  \"lat\": 51.27\n },\n \"weather\": [{\n   \"id\": 800,\n   \"main\": \"Clear\",\n   \"description\": \"clear sky\",\n   \"icon\": \"01d\"\n  }\n ],\n \"base\": \"stations\",\n \"main\": {\n  \"temp\": 285.15,\n  \"pressure\": 1034,\n  \"humidity\": 30,\n  \"temp_min\": 285.15,\n  \"temp_max\": 285.15\n },\n \"visibility\": 10000,\n \"wind\": {\n  \"speed\": 2.6\n },\n \"clouds\": {\n  \"all\": 0\n },\n \"dt\": 1492705200,\n \"sys\": {\n  \"type\": 1,\n  \"id\": 4909,\n  \"message\": 0.2825,\n  \"country\": \"DE\",\n  \"sunrise\": 1492662386,\n  \"sunset\": 1492713582\n },\n \"id\": 2808559,\n \"name\": \"Willich\",\n \"cod\": 200\n}"; 
JSONObject obj = new JSONObject(jsonobj); 
JSONObject jsonObject = obj.getJSONObject("main"); 
System.out.println(jsonObject.get("temp")); 
+0

一行近900個字符。沒有更好的方法嗎? –