Is it ok to save a JSON array in SharedPreferences? Is it ok to save a JSON array in SharedPreferences? android android

Is it ok to save a JSON array in SharedPreferences?


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)


It depends how big the array is. Assuming it's not ridiculously big (less than a few hundred Kb), just store it to shared preferences. If it's bigger than that, you can save it to a file.


to save json array in shared preference you can use method in class as follow

public class CompanyDetails {@SerializedName("id")private String companyId;public String getCompanyId() {    return companyId;}}

in shared preference class

public static final String SHARED_PREF_NAME = "DOC";public static final String COMPANY_DETAILS_STRING = "COMPANY_DETAIL";public static final String USER_DETAILS_STRING = "USER_DETAIL";public static void saveCompanyDetailsSharedPref(Context mContext, CompanyDetails companyDetails){    SharedPreferences mPrefs = mContext.getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);    SharedPreferences.Editor prefsEditor = mPrefs.edit();    Gson gson = new Gson();    String json = gson.toJson(companyDetails);    prefsEditor.putString(COMPANY_DETAILS_STRING, json);    prefsEditor.commit();}public static CompanyDetails getCompanyDetailsSharedPref(Context mContext){    SharedPreferences mPrefs = mContext.getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);    SharedPreferences.Editor prefsEditor = mPrefs.edit();    Gson gson = new Gson();    String json = mPrefs.getString(COMPANY_DETAILS_STRING, "");    if(json.equalsIgnoreCase("")){        return null;    }    CompanyDetails obj = gson.fromJson(json, CompanyDetails.class);    return obj;}

to call value

 private CompanyDetails companyDetails; companyDetails = shared_class.getCompanyDetailsSharedPref(mContext); companyDetails.getCompanyId()