字符串无法转换为JSONObject异常 [英] String cannot be converted to JSONObject exception

查看:760
本文介绍了字符串无法转换为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");

这篇关于字符串无法转换为JSONObject异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆