Parsing JSON, array within an array (Android)

2019-04-12 07:53发布

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();
    }

2条回答
冷血范
2楼-- · 2019-04-12 08:27

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-04-12 08:39

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

查看更多
登录 后发表回答