简体   繁体   English

Android不使用库将字符串反序列化为JSONObject

[英]Android deserialize String to a JSONObject without using libraries

Is there a way to convert a JSON that has been serialised to a String, back to a JSONObject, without having to install additional libraries. 有没有一种方法可以将已序列化为JSON的JSON转换回JSONObject,而无需安装其他库。

I have this JSON: 我有这个JSON:

{
  "asd": false,
  "qwe": false,
  "zxc": false,
  "qaxz": false,
  "asdqwe": false,
  "asdqwe": false,
  "wexd": false
}

Embedded as a String into another JSON object ("user") , by the name "app_settings" 作为字符串嵌入到另一个JSON对象(“用户”)中,名称为“ app_settings”

Then I try this: 然后我尝试一下:

JSONObject settings = user.getJSONObject(JSONKeys.USER_SETTINGS);

Here is the exception that I get: 这是我得到的例外:

    06-20 12:15:19.105: W/System.err(17085):
 org.json.JSONException: Value {"asd":false,"qwe":false,"zxc":false,"qaxz":false,"asdqwe":false,"asdqwe":false,"wexd":false}
 at app_settings of type java.lang.String cannot be converted to JSONObject

SOLUTION

Changed: 已更改:

JSONObject settings = user.getJSONObject(JSONKeys.USER_SETTINGS);

to

JSONObject settings = new JSONObject(user.getString(JSONKeys.USER_SETTINGS));

and it worked 而且有效

有一个采用String构造函数

你可以做

JSONObject obj = new JSONObject(your_string)

只要您的Android项目中已经包含JSONObject库,您就可以简单地使用

JSONObject j = new JSONObject(YOUR STRING);

Rather than doing 而不是做

JSONObject settings = new JSONObject(user.getString(JSONKeys.USER_SETTINGS));

I guess you can use 我想你可以用

JSONObject settings = user.getJSONObject(JSONKeys.USER_SETTINGS);

So as to avoid unnecessary json->string->json parsing. 以免不必要的json-> string-> json解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM