我正试图获得我的json值。首先是我的json。
{
"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
我该如何解决?
答案 0 :(得分:2)
unhandled exception : org.json.JSONException
ANS:您收到该错误因为status
字符串不是 JSON数组
您应该使用 jsonObj.getString("status")
代替 jsonObj.getJSONArray("status");
试试这个
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();
}
<强>输出强>
答案 1 :(得分:1)
未处理的异常:org.json.JSONException
=&GT;因为您正在尝试获取JSON数组,因为它不是JSON数组,而只是一个字段。
尝试:
String status = jsonObj.getString("status");
答案 2 :(得分:1)
try {
JSONObject jsonObj = new JSONObject(result);
String status = jsonObj.getString("status");
JSONObject userData = jsonObj.getJSONObject("userData");
} catch (JSONException e) {
e.printStackTrace();
}
答案 3 :(得分:0)
这里&#34;状态&#34;它不是一个数组,它的字符串。 Json数组应该用[]括起来。 获得&#34; status&#34;的价值你应该使用,
String status = jsonObj.getString("status");
然后你需要检查状态值。 请记住,
由{}
包围的Json对象由[]
括起来的Json数组在获取数据时也使用try-catch块,
try{
String status = jsonObj.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
答案 4 :(得分:-1)
你需要用try / catch包围:
try {
JSONObject jsonObj = new JSONObject(result);
String status = jsonObj.optString("status");
} catch (JSONException e) {
e.printStackTrace();
}