我有一个API服务的响应字符串,如下所示:
{"id":"login","status":"true"}
并且这是解析响应字符串以从密钥“状态”
获取值的方法 JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
}
catch(JSONException e){
e.printStackTrace();
}
JSONArray innerJsonArray = null;
try {
innerJsonArray = jsonObj.getJSONArray("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = innerJsonArray.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(jsonObject.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我有错误 “org.json.JSONArray无法转换为JSONObject”
任何人都可以给我建议吗?
答案 0 :(得分:0)
你在哪一行获得例外?无论如何,你应该使用
jsonObj =JSONObject.fromObject(responseString);
答案 1 :(得分:0)
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
System.out.println(jsonObj.getString("status"));
}
catch(JSONException e){
e.printStackTrace();
}
您不需要打扰任何其他阵列。
答案 2 :(得分:0)
请尝试下面的代码段。试试这个link以获得有关解析JSON响应的更好知识。
JSONObject jObj;
try {
jObj = new JSONObject(responseString);
Log.i("id==", jObj.getString("id"));
Log.i("status==", jObj.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}