小编典典

如何在Android中解析JSON对象

json

我在从JSON对象提取值时遇到一些问题。这是我的代码

try {
    JSONObject json = new JSONObject(result);
    JSONObject json2 = json.getJSONObject("results");
    test = json2.getString("name");     
} catch (JSONException e) {
    e.printStackTrace();
}

test被声明为String。代码运行时显示null。如果将鼠标悬停json2在调试模式下,则可以看到对象中的所有值和名称。

我也试过

test = json2.length();

这回来了test = 0。即使将鼠标悬停在json2对象上,我也可以读取对象中的值。

这是我将使用的JSON字符串的示例。

{
    "caller":"getPoiById",
    "results":
    {
        "indexForPhone":0,
        "indexForEmail":"NULL",
        "indexForHomePage":"NULL",
        "indexForComment":"NULL",
        "phone":"05137-930 68",
        "cleanPhone":"0513793068",
        "internetAccess":"2",
        "overnightStay":"2",
        "wasteDisposal":"2",
        "toilet":"2",
        "electricity":"2",
        "cran":"2",
        "slipway":"2",
        "camping":"2",
        "freshWater":"2",
        "fieldNamesWithValue":["phone"],
        "fieldNameTranslations": ["Telefon"],
        "id":"1470",
        "name":"Marina Rasche Werft GmbH & Co. KG",
        "latitude":"52.3956107286487",
        "longitude":"9.56583023071289"
    }
}

阅读 215

收藏
2020-07-27

共1个答案

小编典典

最后,我使用JSONObject.get而不是来解决它JSONObject.getString,然后将其强制test转换为String

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
2020-07-27