-2

To Store JSON object to String is possible. But Is there any way to store the JSON Object as it is in Shared Preferences and retrieve too?

JSONObject data_obj = new JSONObject();

JSONArray arr_obj = new JSONArray();
JSONObject main_obj = new JSONObject();

data_obj.put("id", "1");
data_obj.put("name", "Loin");

arr_obj.put(data_obj);
main_obj.put("user_review", arr_obj);

How will main_obj be store in Shared Preferences?

Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
Luvnish Monga
  • 7,072
  • 3
  • 23
  • 30

2 Answers2

2

You can convert JsonObject to String and put that string in Shared preference and can do reverse to get JsonObject.

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.

For example,

String myString = new JSONObject().put("JSON", "Hello, World!").toString();
print(myString) it produces the string {"JSON": "Hello, World"}.

and for reverser you can do JSONObject myJSON = new JSONObject(myString);

For SharedPreference you can refer

Reference

Shadow Droid
  • 1,696
  • 1
  • 12
  • 26
1

JSONObject is ultimately a key/value pairs string, so convert it into the string using toString() and save it!

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295