gpt4 book ai didi

java - Android中解析JSON数组和对象

转载 作者:行者123 更新时间:2023-12-01 06:34:44 25 4
gpt4 key购买 nike

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 代码解析它:

JSONObject jObj = null; 尝试 { 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。

此外,如果数组中有多个部分,我们如何确保它们中的每一个都被打印出来?

最佳答案

您的 JSON 字符串以 JSONArray 开头。

这里是示例代码,请尝试一下。

    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 Parsing Tutorial

关于java - Android中解析JSON数组和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28736419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com