在Android中解析JSON数组和对象 [英] Parsing JSON array and object in Android

查看:108
本文介绍了在Android中解析JSON数组和对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是JSON的样子:

[{
    "pmid": "2",
    "name": " MANAGEMENT",
    "result": "1",
    "properties": [
        {
            "prop_id": "32",
            "prop_name": "Bonneville",
            "address": "122 Lakeshore",
            "city": "Ripley",
            "state": "OH",
            "zip": "11454",
            "lat": "41.123",
            "long": "-85.5034"
        }
    ]
}]

我正在尝试使用Android中的以下Java代码来解析它:

I am trying to parse it with the following Java code in Android:

JSONObject jObj = null; 尝试 { jObj =新的JSONObject(jsonStr);

JSONObject jObj = null; try { jObj = new JSONObject(jsonStr);

    // We get weather info (This is an array)
    JSONArray jArr = jObj.getJSONArray("properties");

    // We use only the first value
    //JSONObject JSONWeather = jArr.getJSONObject(0);
    JSONObject c = jArr.getJSONObject(0);
    String name = c.getString(TAG_NAME);
    String email = c.getString(TAG_EMAIL);
    String phone = c.getString(TAG_PHONE);
} catch (JSONException e) {
    e.printStackTrace();
}

return null;

虽然我没有得到任何结果.如何成功解析此JSON?我正在使用Android Studio.

I am not getting any results though. How can I successfully parse this JSON? I'm using Android Studio.

此外,如果阵列中有多个零件,我们如何确保将每个零件都打印出来?

Also, if there were multiple pieces to the array, how could we make sure each one of them is printed out?

推荐答案

您的JSON字符串以JSONArray开头.

Your JSON string start with JSONArray.

这里有示例代码,请尝试一下.

Here sample code, try it.

    JSONArray mJsonArray = new JSONArray(jsonStr);
    JSONObject mJsonObject = mJsonArray.getJSONObject(0);

    String pmid = mJsonObject.getString("pmid");
    String name = mJsonObject.getString("name");
    String result = mJsonObject.getString("result");


    JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
    for (int i = 0; i < mJsonArrayProperty.length(); i++) {
        JSONObject mJsonObjectProperty = mJsonArrayProperty.getJSONObject(i);

        String prop_id = mJsonObjectProperty.getString("prop_id");
        String prop_name = mJsonObjectProperty.getString("prop_name");
        String address = mJsonObjectProperty.getString("address");
        String city = mJsonObjectProperty.getString("city");
        String state = mJsonObjectProperty.getString("state");
        String zip = mJsonObjectProperty.getString("zip");
        String lat = mJsonObjectProperty.getString("lat");
        String lon = mJsonObjectProperty.getString("long");
    }

检查 Android JSON解析教程

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

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