Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to save a JSON array in SharedPreferences?

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?

like image 490
Sheehan Alam Avatar asked May 07 '11 00:05

Sheehan Alam


People also ask

Can we store JSON in SharedPreferences?

In Android, SharedPreferences class can save only these: We use the GSON library to convert the model class to JSON String and we save that JSON String into the SharedPreferences.

Can I save array list in SharedPreferences?

We can store data in the form of key and value pairs using Shared Preferences. In this article, we will take a look at How to Save Array List to SharedPreferences in Android using Kotlin.

How do I save an Arraylist of custom objects to SharedPreferences?

SharedPreferences appSharedPrefs = PreferenceManager . getDefaultSharedPreferences(this. getApplicationContext()); Gson gson = new Gson(); String json = appSharedPrefs. getString("MyObject", ""); Student mStudentObject = gson.

Can we store objects in SharedPreferences?

We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference.


1 Answers

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)

like image 138
sgarman Avatar answered Sep 18 '22 11:09

sgarman