如何在Android中解析JSON对象

时间:2011-04-06 12:53:42

标签: android 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"
    }
}

4 个答案:

答案 0 :(得分:47)

最后,我使用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();
    }
}

答案 1 :(得分:11)

在您的JSON格式中,它没有启动JSON对象

喜欢:

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

以上Json以info作为JSON对象开头。所以在执行时:

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

现在,我们可以访问result字段:

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

我认为这是遗漏的,所以当我们使用JSONTokener之类的答案时问题就解决了。

你的答案非常好。我想我添加这些信息所以我回答了

谢谢

答案 2 :(得分:10)

答案 3 :(得分:5)

JSONArray jsonArray = new JSONArray(yourJsonString);

for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject obj1 = jsonArray.getJSONObject(i);
     JSONArray results = patient.getJSONArray("results");
     String indexForPhone =  patientProfile.getJSONObject(0).getString("indexForPhone"));
}

更改为JSONArray,然后转换为JSONObject。