简体   繁体   中英

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.

I have this 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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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