Search code examples
androidandroid-sharedpreferences

How to store and get JSON Object from Shared Preferences in android


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?


Solution

  • 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