tlxwiggum tlxwiggum - 1 month ago 21
Java Question

Android - How to parse specific values from JSON Array and display Toast

New to Android and Java in general and I'm learning how to make a JSON call. To do so, I'm following this guide: http://mobiforge.com/design-development/consuming-json-services-android-apps

Here's where things get confusing for me. The author of that tutorial wants the reader to call this API: http://ws.geonames.org/findNearByWeatherJSON?lat=37lng=122

Which returns a JSON object in this format:

{
"weatherObservation": {
"clouds":"scattered clouds",
"weatherCondition":"n/a",
"observation":"KCFV 090852Z AUTO 06005KT
10SM SCT090 SCT110 24/20 A3000 RMK AO2
SLP148 T02390200 53002",
"windDirection":60,
"ICAO":"KCFV",
"seaLevelPressure":1014.8,
"elevation":225,
"countryCode":"US",
"lng":-95.56666666666666,
"temperature":"23.9",
"dewPoint":"20",
"windSpeed":"05",
"humidity":78,
"stationName":"Coffeyville, Coffeyville
Municipal Airport",
"datetime":"2012-07-09 08:52:00",
"lat":37.083333333333336
}
}


Pretty straight forward, except that the API is no longer valid/has limits. In order to finish the project I've instead opted to call this API: http://api.openweathermap.org/data/2.5/weather?lat=37.77&lon=-122.419

Which returns the JSON in this format

{
"coord": {
"lon": 139,
"lat": 35
},
"sys": {
"country": "JP",
"sunrise": 1369769524,
"sunset": 1369821049
},
"weather": [
{
"id": 804,
"main": "clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"main": {
"temp": 289.5,
"humidity": 89,
"pressure": 1013,
"temp_min": 287.04,
"temp_max": 292.04
},
"wind": {
"speed": 7.31,
"deg": 187.002
},
"rain": {
"3h": 0
},
"clouds": {
"all": 92
},
"dt": 1369824698,
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}


I can make the call just fine, but how do I display the "main" and "description" strings in the "weather" array? More specifically, how do I display this information as a Toast?

Here's what I have:

protected void onPostExecute(String result){

try {


JSONArray weatherArray = new JSONArray(result);
JSONArray wArray = new JSONArray("weather");

String mainWeather = wArray.getString(1);
String mainDescription = wArray.getString(2);

Toast.makeText(getBaseContext(), mainWeather + " - "
+ mainDescription,Toast.LENGTH_SHORT).show();

} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}


BecauseI am following the mobiforge Tutorial, I have not deviated anywhere else except for this particular block of code.

Thanks for the help!

Edit:
There are several solutions here that work see @swats and @user3515851. I have chosen @remees-m-syde due to it's simplicity. Primarily because his solution did not require that I go through the for loop.

Answer

You are unable to get the data because there is one json object inside the "weather" JSONArray.

JSONArray starts with - [

JSONObject starts with - {,

So first get the JSONArray and then the JSONObject inside it.

"weather": [                          ----Array
        {                             ----Object
            "id": 804,
            "main": "clouds",
            "description": "overcast clouds",
            "icon": "04n"
        }
    ]

You have to get this JSONObject and then get the String from it like the below code showing.

    JSONObject weatherArray = new JSONObject(result);
    JSONArray wArray = weatherArray.getJSONArray("weather");
    JSONObject jobj = wArray.getJSONObject(0);
    String mainWeather = jobj.getString("main");
    String mainDescription = jobj.getString("description");
    Toast.makeText(getBaseContext(), mainWeather + " - "
                                + mainDescription,Toast.LENGTH_SHORT).show();

When there is multiple object in Array, Get it as below.

JSONObject rootJsonObj = new JSONObject(result);
     JSONArray wArray = rootJsonObj.optJSONArray("weather");
     for (int i = 0; i < wArray.length(); i++) {
          JSONObject weatherJsonObj = wArray.getJSONObject(i);
          String mainWeather = weatherJsonObj.getString("main");
          String mainDescription = weatherJsonObj.getString("description");

          Toast.makeText(getBaseContext(), mainWeather + " - "
                      + mainDescription,Toast.LENGTH_SHORT).show();
     }