【问题标题】:Fetch temperature from JSON从 JSON 中获取温度
【发布时间】:2016-10-01 06:23:15
【问题描述】:

我正在构建一个 Android 应用程序,我想在其中读取我所在城市的当前温度。我正在使用http://openweathermap.org/current 免费 API。

现在,当我尝试通过执行以下操作获取温度时:

@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");
            .
            .

“desc”或描述如预期般被取,购买温度的取值说:

W/System.err: org.json.JSONException: main 没有值 W/System.err:在 org.json.JSONObject.get(JSONObject.java:389) W/System.err:在 org.json.JSONObject.getJSONObject(JSONObject.java:609)

这是我收到的 JSON 的 sn-p,注意 "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"}] ...

我在获取时做错了什么?

【问题讨论】:

  • 您的 JSON 无效,请检查,这是原始 JSON 还是您为发布目的而编辑的,您将纬度/经度定义为 xxx
  • JSON 是我收到的 JSON 的一个片段,注意 "lon":xxx,"lat":xxx 是故意的。 ;-)

标签: java android json


【解决方案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");

【讨论】:

  • 双温度 = 测量值.getJSONObject("main").getDouble("temp");这是无效的,它说:“错误:(92, 78) 错误:不兼容的类型:字符串无法转换为 int”
  • 双温度 = 测量值.getJSONObject("main").getDouble(0);试试这个
  • 问题出在 getJSONObject("main") 上。
【解决方案2】:

以下给出错误。

JSONObject currentTemp = response.getJSONObject("main");

main 不在顶层,你获取的方式是错误的。

【讨论】:

  • 行“双温度=测量.getJSONObject("main").getDouble(0);"无效(错误:不兼容的类型:字符串无法转换为 int)。问题出在 getJSONObject("main")
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 2014-06-12
  • 2012-09-03
  • 1970-01-01
  • 2017-07-17
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多