解析雅虎针对天气预报的API响应

时间:2018-04-07 06:46:24

标签: android json yahoo-api

我正在使用Yahoo API创建天气应用程序。我想得到一个预测。

我尝试过使用JSONObject

 JSONObject jobj2 = new JSONObject(response);
 JSONArray jsonArray2 = jobj2.getJSONArray("forcast");
 for (int i = 0; i < jsonArray2.length(); i++) {
    ....
 }

但这显示错误。

这是我需要处理的API响应:

{
  "query": {
    "count": 1,
    "created": "2018-04-07T05:03:39Z",
    "lang": "en-us",
    "results": {
      "channel": {
        "units": {
          "distance": "mi",
          "pressure": "in",
          "speed": "mph",
          "temperature": "F"
        },
        "title": "Yahoo! Weather - London, England, GB",
        "link": "...",
        "description": "Yahoo! Weather for London, England, GB",
        "language": "en-us",
        "lastBuildDate": "Sat, 07 Apr 2018 06:03 AM BST",
        "ttl": "60",
        "location": {
          "city": "London",
          "country": "United Kingdom",
          "region": " England"
        },
        "wind": {
          "chill": "48",
          "direction": "90",
          "speed": "7"
        },
        "atmosphere": {
          "humidity": "78",
          "pressure": "1002.0",
          "rising": "0",
          "visibility": "16.1"
        },
        "astronomy": {
          "sunrise": "6:21 am",
          "sunset": "7:45 pm"
        },
        "image": {
          "title": "Yahoo! Weather",
          "width": "142",
          "height": "18",
          "link": "http://weather.yahoo.com",
          "url": "http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
        },
        "item": {
          "title": "Conditions for London, England, GB at 05:00 AM BST",
          "lat": "51.506401",
          "long": "-0.12721",
          "link": "...",
          "pubDate": "Sat, 07 Apr 2018 05:00 AM BST",
          "condition": {
            "code": "26",
            "date": "Sat, 07 Apr 2018 05:00 AM BST",
            "temp": "49",
            "text": "Cloudy"
          },
          "forecast": [
            {
              "code": "26",
              "date": "07 Apr 2018",
              "day": "Sat",
              "high": "60",
              "low": "50",
              "text": "Cloudy"
            },
            {
              "code": "12",
              "date": "08 Apr 2018",
              "day": "Sun",
              "high": "53",
              "low": "48",
              "text": "Rain"
            }
          ],
          "description": "...",
          "guid": {
            "isPermaLink": "false"
          }
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:1)

&#34;预测&#34;嵌套在query&gt;下results&gt; item&gt; JSON响应中的forecast。使用getJSONArray("forcast"),您试图从根级别获取它,这是错误的。

您需要遍历树以获得嵌套&#34;预测&#34;节点。看一下解决同一问题的How to access nested elements of json object using getJSONArray method