无法从嵌套下载的JSON中获取字符串

时间:2018-01-09 11:48:18

标签: android json android-studio

我从服务器获取JSON:

                JSONObject vkjson = response.json;

我试过把它变成一个字符串并通过LogCat检查以确保它有效 - 是的,它100%有效。 但它是嵌套的:

{"response":{"first_name":"...","last_name":"..."} }

我试过这样做:

       String result = vkjson.getJSONObject("response").getString("first_name");

但IDE不喜欢getJSONObject部分并强调它。 IDE说:

  

org.json.JSONException中未处理的异常

怎么了?是因为JSON是从服务器加载还是代码不正确?

提前谢谢。

4 个答案:

答案 0 :(得分:0)

除了不处理可能抛出的JSONException之外,你的代码没有任何问题(即如果没有一个名为“response”的对象会发生什么)。

您需要查看异常处理并将此代码包装在try .. catch块中或以其他方式处理异常。

Java exception handling

答案 1 :(得分:0)

  

org.json.JSONException中未处理的异常

意味着该方法可以抛出JSONException并且您必须处理它。

所以你必须:

try {
     String result = vkjson.getJSONObject("response").getString("first_name");
} catch (JSONException exception){
            //Handle exception here
}

答案 2 :(得分:0)

这样做 - :

try
{
 JSONObject vkjson = response.json;

  //More code related to json
}

catch(JsonException e)
{
   e.printStackTrace();
}

答案 3 :(得分:0)

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(responseString);
                if(jsonObject != null)
                {
                    if (jsonObject.has("response")) {
                        JSONObject responseObject = jsonObject.getJSONObject("response");
                        String firstName = responseObject.getString("first_name");
                        Log.d("Tag",firstName);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }