Is it ok to save a JSON array in SharedPreferences?

Sheehan Alam picture Sheehan Alam · May 7, 2011 · Viewed 40.6k times · Source

I have a JSON Array that I need to save. I was thinking about serializing it, but would it be better to just save it as a string in SharedPreferences and then rebuild it when I need to read it in?

Answer

sgarman picture sgarman · May 7, 2011

The JSON object in Java does not implement serialaizable out of the box. I have seen others extend the class to allow that but for your situation I would simply recommend storing the JSON object as a string and using its toString() function. I have had success with this.

editor.putString("jsondata", jobj.toString());

And to get it back:

String strJson = sharedPref.getString("jsondata","0");//second parameter is necessary ie.,Value to return if this preference does not exist. 

if (strJson != null) {
           try {
               JSONObject response = new JSONObject(strJson);

         } catch (JSONException e) {

         }
  }

http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)