Search code examples
javaandroidjsonyahoo-weather-api

Parse YahooWeather JSON response


I try to make a simple weather app and for that I use YahooWeather api. So I get a response something like this:

/**/yqlCallback({
    "query": {
        "count": 3,
        "results": {
            "channel": [{
                "item": {
                    "pubDate": "Fri, 16 Jan 2015 11:00 am EET",
                    "condition": {
                        "temp": "1",
                        "text": "Cloudy"
                    },
                }
            },
            {
                "item": {
                    "title": "1",

                }
            },
            {
                "item": {
                    "title": "2",

                }

            }]
        }
    }
});

The only data's I need from here is pubDate, temp and text. So here is how I try to get those values.

    JSONObject main = json.getJSONObject("query").getJSONObject("result").getJSONArray("channel")
    .getJSONObject(0);
    JSONObject details = main.getJSONObject("condition");
String t1 = details.getString("text");
String t2 = details.getString("temp");
String t3 = main.getString("pubDate");

This give's me this error: One or more fields not found in the JSON data.


Solution

  • In current json no JSONObject present with result key. Use results instead of result to get JSONObejct from query JSONObject:

    JSONObject main = json.getJSONObject("query").
                    getJSONObject("results").getJSONArray("channel");
    JSONObject items = main.getJSONObject("item");
    JSONObject details = items.getJSONObject("condition");
    String t1 = details.getString("text");
    String t2 = details.getString("temp");