Android 如何解析json并检查其值?
我正在尝试获取json的值。首先是我的jsonAndroid 如何解析json并检查其值?,android,json,Android,Json,我正在尝试获取json的值。首先是我的json { "status": "true", "userData": { "user_id": "USER001", "username": "boby", "password": "c83e4046a7c5d3c4bf4c292e1e6ec681", "fullname": "Boby Kurniawan", "phone": "089688xxxxxxx"
{
"status": "true",
"userData": {
"user_id": "USER001",
"username": "boby",
"password": "c83e4046a7c5d3c4bf4c292e1e6ec681",
"fullname": "Boby Kurniawan",
"phone": "089688xxxxxxx",
"profilpic": null,
"status": null,
"flag": 1,
"tipe": "TP001",
"Deskripsi": "Ini tentang gua",
"Email": "boby@mail.com"
}
}
好的,对于第一个,将有2个json,如果登录成功,json将如上所示,但是当它失败时,它将返回
{ "status" : "false" }
所以我需要正确解析它?所以我加上这一行
JSONObject jsonObj = new JSONObject(result);
JSONArray status = jsonObj.getJSONArray("status");
但是我得到了这个错误
unhandled exception : org.json.JSONException
我怎样才能修好它
未处理的异常:org.json.JSONException
ANS:您收到该错误是因为status
不是JSON数组
您应该使用jsonObj.getString(“状态”)
而不是jsonObj.getJSONArray(“状态”)代码>
试试这个
try
{
JSONObject jsonObj = new JSONObject(result);
String status = jsonObj.getString("status");
Log.i("status", "->" + status);
JSONObject jsonObject = jsonObj.getJSONObject("userData");
Log.i("user_id", "->" + jsonObject.getString("user_id"));
Log.i("username", "->" + jsonObject.getString("username"));
Log.i("password", "->" + jsonObject.getString("password"));
Log.i("fullname", "->" + jsonObject.getString("fullname"));
Log.i("phone", "->" + jsonObject.getString("phone"));
Log.i("profilpic", "->" + jsonObject.getString("profilpic"));
Log.i("status", "->" + jsonObject.getString("status"));
Log.i("flag", "->" + jsonObject.getString("flag"));
Log.i("tipe", "->" + jsonObject.getString("tipe"));
Log.i("Deskripsi", "->" + jsonObject.getString("Deskripsi"));
Log.i("Email", "->" + jsonObject.getString("Email"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
输出
未处理的异常:org.json.JSONException
=>因为您正在尝试获取JSON数组,因为它不是JSON数组,只是一个字段
尝试:
您需要围绕一个try/catch:
try {
JSONObject jsonObj = new JSONObject(result);
String status = jsonObj.optString("status");
} catch (JSONException e) {
e.printStackTrace();
}
这里的“status”不是数组,而是字符串。Json数组应包含在[]中。
要获得“状态”的值,您应该使用
String status = jsonObj.getString("status");
然后您需要检查状态值。
记住
由{}包围的Json对象
由[]括起的Json数组
在获取数据时也使用try-catch块
try{
String status = jsonObj.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
请检查我的ans。请使用异常处理检查我的ans。可能重复错误的ans检查状态是字符串而不是json数组您是对的。。。复制粘贴后我忘了更改:)修复。。。另外,最好使用optString()而不是getString()@YVS1102。我很乐意帮助您。
String status = jsonObj.getString("status");
try{
String status = jsonObj.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}