繁体   English   中英

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

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

有没有一种方法可以将已序列化为JSON的JSON转换回JSONObject,而无需安装其他库。

我有这个JSON:

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

作为字符串嵌入到另一个JSON对象(“用户”)中,名称为“ app_settings”

然后我尝试一下:

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

这是我得到的例外:

    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

已更改:

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

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

而且有效

有一个采用String构造函数

你可以做

JSONObject obj = new JSONObject(your_string)

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

JSONObject j = new JSONObject(YOUR STRING);

而不是做

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

我想你可以用

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

以免不必要的json-> string-> json解析。

暂无
暂无

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

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