解析来自 Volley 的简单 json 响应
Parsing simple json response from Volley
我正在尝试解析来自 Volley 的 JSON 响应。
我的"response"参数是:
{"result":["{\"success\":\"false\"}"]}
我在以下位置遇到错误:JSONObject jo=ja.getJSONObject(0); //Error here
我做错了什么?
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("result");
JSONObject jo=ja.getJSONObject(0); //Error here
String rst=jo.getString("success");
if (rst.equals("true")) {
///do something
} else{
///do something
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
改变这个
JSONArray ja = response.getJSONArray("result");
JSONObject jo=ja.getJSONObject(0);
至此
JSONObject jo = new JSONObject(response)
JSONArray ja=j0.getJSONArray("result");
您必须先从响应中创建 json 对象。然后从 JsonObject 中获取 json 数组...
问题是,您的 json 数组包含的字符串不是 JSONObject
。在您的 JSON {"result":["{\"success\":\"false\"}"]}
中,元素 "{\"success\":\"false\"}"
是字符串,这意味着您的 JSONArray
包含 Strings
而不是 JSONObject
。所以你需要将元素解析为 String
然后将它们解析为 JSONObject
.
您可以将代码编写为
JSONArray ja = jb.getJSONArray("result");
for(int i=0; i<ja.length(); i++) {
String stringElement = ja.getString(i);
// Then you can parse it with JSONObject
JSONObject resultObject = new JSONObject(stringElement);
}
仅供参考,您期望的 JSON 是 {"result":[{"success":"false"}]}
我正在尝试解析来自 Volley 的 JSON 响应。
我的"response"参数是:
{"result":["{\"success\":\"false\"}"]}
我在以下位置遇到错误:JSONObject jo=ja.getJSONObject(0); //Error here
我做错了什么?
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("result");
JSONObject jo=ja.getJSONObject(0); //Error here
String rst=jo.getString("success");
if (rst.equals("true")) {
///do something
} else{
///do something
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
改变这个
JSONArray ja = response.getJSONArray("result");
JSONObject jo=ja.getJSONObject(0);
至此
JSONObject jo = new JSONObject(response)
JSONArray ja=j0.getJSONArray("result");
您必须先从响应中创建 json 对象。然后从 JsonObject 中获取 json 数组...
问题是,您的 json 数组包含的字符串不是 JSONObject
。在您的 JSON {"result":["{\"success\":\"false\"}"]}
中,元素 "{\"success\":\"false\"}"
是字符串,这意味着您的 JSONArray
包含 Strings
而不是 JSONObject
。所以你需要将元素解析为 String
然后将它们解析为 JSONObject
.
您可以将代码编写为
JSONArray ja = jb.getJSONArray("result");
for(int i=0; i<ja.length(); i++) {
String stringElement = ja.getString(i);
// Then you can parse it with JSONObject
JSONObject resultObject = new JSONObject(stringElement);
}
仅供参考,您期望的 JSON 是 {"result":[{"success":"false"}]}