解析JSON,数组中的数组(Android)

问题描述:

我正在尝试从 http://www.worldweatheronline.com JSON Feed中解析天气信息.这是它的格式:

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"
      } ],

所以有current_condition JSONArray,我设法从中获取值.但是,如何从内部数组weatherDescweatherIconUrl中读取值?

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?

这是我用于读取precipMMpressuretemp_C等的代码:

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

就像

current_condition.getJSONArray()

与json解析一样,我建议您看一下这个库 http://jackson.codehaus.org/

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

编辑发表评论后

您发布的代码可以进行很多改进.您正在遍历数组中的每个值.您可以对数组执行相同的操作.只需调用.getJsonArray(),而不是.getJsonObject().但是,这意味着您的代码为其他每个值都引发了错误.我会再次推荐杰克逊图书馆

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