如何在Android中解析JSON对象

jid*_*vah 25 android json

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

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

test被宣布为String.当代码运行时,它正在显示null.如果我json2在调试模式下悬停,我可以看到对象中的所有值和名称.

我也试过了

test = json2.length();
Run Code Online (Sandbox Code Playgroud)

这回来了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"
    }
}
Run Code Online (Sandbox Code Playgroud)

jid*_*vah 47

最后我通过使用JSONObject.get而不是JSONObject.getString然后转换test为a 来解决它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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Kus*_*hal 12

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

喜欢 :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

Json上面info以JSON对象开头.所以执行时:

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

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

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

我认为这是缺失的,所以当我们使用JSONTokener你的答案时,问题就解决了.

你的答案非常好.只是我想我添加这些信息所以我回答

谢谢


小智 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"));
}
Run Code Online (Sandbox Code Playgroud)

切换到JSONArray,然后转换为JSONObject.