我从服务器获取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是从服务器加载还是代码不正确?
提前谢谢。
答案 0 :(得分:0)
除了不处理可能抛出的JSONException
之外,你的代码没有任何问题(即如果没有一个名为“response”的对象会发生什么)。
您需要查看异常处理并将此代码包装在try .. catch
块中或以其他方式处理异常。
答案 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();
}