Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON, array within an array (Android)

I'm trying to parse weather information from a http://www.worldweatheronline.com JSON feed. This is the format that it comes in:

{ "data" : { "current_condition" : [ { "cloudcover" : "75",
        "humidity" : "100",
        "observation_time" : "10:01 PM",
        "precipMM" : "0.0",
        "pressure" : "1015",
        "temp_C" : "3",
        "temp_F" : "37",
        "visibility" : "4",
        "weatherCode" : "143",
        "weatherDesc" : [ { "value" : "Mist" } ],
        "weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0006_mist.png" } ],
        "winddir16Point" : "N",
        "winddirDegree" : "360",
        "windspeedKmph" : "11",
        "windspeedMiles" : "7"
      } ],

So there is the current_condition JSONArray, which I have managed to obtain values from. But then how do I read the values from the inner arrays weatherDesc or weatherIconUrl?

Here is my code for reading precipMM, pressure, temp_C, etc:

String precipMM = null;
    try {
        JSONObject data = json.getJSONObject("data");

        JSONArray current_condition = data.getJSONArray("current_condition");

        for(int i = 0; i < current_condition.length(); i++) {
            precipMM = current_condition.getJSONObject(i).getString("precipMM");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
like image 253
Matt Harris Avatar asked May 10 '26 16:05

Matt Harris


2 Answers

It's as simple as

current_condition.getJSONArray()

As also with json parsing I would suggest looking at this library http://jackson.codehaus.org/

EDIT After you comment

The code you posted could be improved a lot. You are iterating through the array for each value. You can do the same thing with the array. Just call .getJsonArray(), instead of .getJsonObject(). However this means your code is throwing an error for each of the other values. I would again recommend the Jackson library

like image 73
jiduvah Avatar answered May 12 '26 05:05

jiduvah


weatherDesc and weatherIconUrl are provided as array, so you can access by item i.e. inside a for loop.

Just use same command as you do it for current_condition

like image 39
Chris Avatar answered May 12 '26 07:05

Chris