解析JSON,数组中的数组(Android) [英] Parsing JSON, array within an array (Android)

查看:313
本文介绍了解析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

这篇关于解析JSON,数组中的数组(Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆