2016-09-30 53 views
0

我正在構建一個Android應用程序,我想要讀取我所在城市的當前溫度。我正在使用免費的http://openweathermap.org/current API。從JSON獲取溫度

現在,當我當我嘗試這樣做,以獲取溫度以下幾點:

@Override 
    public void onResponse(JSONObject response) { 

     try { 

      Log.d("MY LOGGER: ", "Task started"); 

      //Fetch description 
      JSONArray measurements = response.getJSONArray("list"); 
      String desc = measurements.getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description"); 

      //Fetch temp 
      JSONObject currentTemp = response.getJSONObject("main"); 
      double temp = currentTemp.getDouble("temp"); 
      . 
      . 

的「遞減」或描述如預期牽強,買的溫度取說:

W/System.err: org.json.JSONException: No value for main W/System.err: at org.json.JSONObject.get(JSONObject.java:389) W/System.err: at org.json.JSONObject.getJSONObject(JSONObject.java:609)

這是我收到的JSON的一個片段,注意 「LON」:XXX 「LAT」:xxx是故意的:

{"city":{"id":2624652,"name":"Arhus","coord":{"lon":xxx,"lat":xxx},"country":"DK","population":0,"sys":{"population":0}},"cod":"200","message":0.0028,"cnt":40,"list":[{"dt":1475269200,"main":{"temp":284.9,"temp_min":284.897,"temp_max":284.9,"pressure":1017.03,"sea_level":1020.8,"grnd_level":1017.03,"humidity":79,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"clouds":{"all":48},"wind":{"speed":6.75,"deg":247.005},"rain":{"3h":0.04},"sys":{"pod":"n"},"dt_txt":"2016-09-30 21:00:00"},{"dt":1475280000,"main":{"temp":284.21,"temp_min":284.205,"temp_max":284.21,"pressure":1017.5,"sea_level":1021.27,"grnd_level":1017.5,"humidity":87,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}] ... 

我在抓取中做錯了什麼?

+0

您的JSON是無效的,請檢查一下,原來這就是JSON或您張貼目的編輯,你必須定義爲XXX –

+0

經/緯度的JSON是我收到的JSON的剪斷,說明「LON 「:xxx,」lat「:xxx是故意的。 ;-) – Jakob

回答

1

修訂

嘗試獲取這種方式。

 JSONArray measurements = response.getJSONArray("list"); 
       //description     
       String desc = measurements.getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description"); 
       //temperature 
       double temp = measurements.getJSONObject(0).getJSONObject("main").getDouble("temp"); 
+0

double temp = measurements.getJSONObject(「main」)。getDouble(「temp」); 這是無效的它說:「錯誤:(92,78)錯誤:不兼容的類型:字符串不能轉換爲int」 – Jakob

+0

double temp = measurements.getJSONObject(「main」)。getDouble(0);試試這個 –

+0

它是getJSONObject(「main」)就是問題所在。 – Jakob

1

以下是給出的錯誤。

JSONObject currentTemp = response.getJSONObject(「main」);

主不在頂層,您提取的方式是錯誤的。

+0

「double temp = measurements.getJSONObject(」main「)。getDouble(0);」無效(錯誤:不兼容的類型:字符串不能轉換爲int)。它是getJSONObject(「main」)是問題 – Jakob