字符串无法转换为JSONObject异常
问题描述:
这里是Json的新手,我尝试运行以下代码时遇到java.lang.String类型的 Value数据库无法转换为JSONObject 错误的情况.其他答案在这里.
Newbie to Json here, I'm gettin a Value Database of type java.lang.String cannot be converted to JSONObject error when I try and run the following code.I cant make any sense of other answers on here.
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JN = jsonArray.getJSONObject(0);
String code =JN.getString("code");
String message = JN.getString("message");
if (code.equals("reg_true"))
{
showDialog("Your Registration has been successful.",message,code);
}
else if (code.equals("reg_false"))
{
showDialog("Your Registration Failed.",message,code);
}
} catch (JSONException e){
e.printStackTrace();
}
这是错误
W/System.err﹕ org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONObject
W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err﹕ at com.example.project.BackgroundTask.onPostExecute(BackgroundTask.java:133)
W/System.err﹕ at com.example.project.BackgroundTask.onPostExecute(BackgroundTask.java:29)
答
您发布的Json无效,请修剪{"server_response
并关闭花括号.
剩下的Json会像这样,现在有效,
The Json you are posting is invalid, trim that {"server_response
and closing curly braces too.
The remaining Json will be like this, which is valid now,
[{"code":"reg_true","message":"Sucessful registration.Thank you.Enjoy"}]
您可以在此处进行解析,
JSONArray jsonarray = new JSONArray(json);
JSONObject jsonobject = jsonarray.getJSONObject(0);
String code = jsonobject.getString("code");
String message = jsonobject.getString("message");
更新:
如果您的Json符合您的评论,那么您可以像这样轻松地检索
If your Json is as you commented then you can easily retrieve this like
JSONObject jobject = new JSONObject(json);
JSONArray jsonarray = jobject.getJSONArray("server_response");
JSONObject jsonobject = jsonarray.getJSONObject(0);
String code = jsonobject.getString("code");
String message = jsonobject.getString("message");