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?
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.
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.
SharedPreferences appSharedPrefs = PreferenceManager . getDefaultSharedPreferences(this. getApplicationContext()); Gson gson = new Gson(); String json = appSharedPrefs. getString("MyObject", ""); Student mStudentObject = gson.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With