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?
-
3a JSON array is already serialized, so what do you mean exactly? – Juan Gomez May 07 '11 at 00:35
-
I want to save it to a file so I can read it again later. My alternative is to put it in SharedPreferences. – Sheehan Alam May 07 '11 at 01:00
9 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)

- 6,085
- 1
- 22
- 40

- 6,152
- 5
- 40
- 44
-
Thanks How then to convert it back to a JSONArray? I can see a toJSONArray(names) method but it needs names or keyvalue parameters :s – Declan McKenna Apr 16 '12 at 22:44
-
This is not the most performance way of doing, since there will be double parsing. One pass to convert the array to JSON, another pass to convert the JSON to XML. If this is done in a critical path like from the main thread it can cause performance issues. – Kiran Kumar Apr 23 '20 at 09:34
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.

- 47,727
- 41
- 151
- 191
-
i have a Json array of 40 items with 5 or 6 attributes in each item of a list, is it a good idea to use Sharedpreferences? – Jay Dangar Sep 19 '18 at 11:46
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()

- 348
- 3
- 7
-
-
As you can see in the code stored string is in the form of json so if you want to get json from shared preference now you can get that easily you can modify it in your way i just put that into pojo to simplify , thanks for feedback – Mahesh Pandit Oct 26 '20 at 12:42
I have done the same thing ... serialize an objet to a json string and save it into shared prefs. No problem, but understand that ultimately the prefs are an XML file, so if you are reading / writing it a lot, it isn't going to perform well.

- 22,176
- 9
- 79
- 134
Yes, You can save.
public void saveData(View view) {
User user = new User(1, "Rajneesh", "hi this is rajneesh shukla");
userList.add(user);
SharedPreferences preferences = getSharedPreferences("DATA" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String s = gson.toJson(userList);
editor.putString("USER_DATA", s);
editor.apply();
}
public void logData(View view) {
SharedPreferences preferences = getSharedPreferences("DATA", MODE_PRIVATE);
String s = preferences.getString("USER_DATA", "Data is not saved" );
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<User>>(){} .getType();
ArrayList<User> mUser = gson.fromJson(s, type);
}

- 1,048
- 13
- 21
Save the JSON directly out. Look at it this way: you're encapsulating the data representation. If you serialized out a specific object format, you'd be stuck with that object format or have to deal with possible changes to that object and worry about upgrading from an old serialization format to a new one in the future. Saving it off as JSON you can inflate it however you desire.

- 8,136
- 3
- 25
- 29
Here's a simple version using Kotlin to store a User class:
class PreferenceHelper(context: Context) {
companion object {
private const val prefsFileName = "com.example.prefs"
private const val userConst = "user"
}
private val prefs: SharedPreferences = context.getSharedPreferences(prefsFileName, MODE_PRIVATE)
var user: User?
get() = GsonBuilder().create().fromJson(prefs.getString(userConst, null), User::class.java)
set(value) = prefs.edit().putString(userConst, GsonBuilder().create().toJson(value)).apply()
}

- 2,561
- 3
- 35
- 49
Another Easy Way To Save JsonArray Into Sharedprefrences :
public void SaveFriendList(String key, JSONArray value) {
FriendLst = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = FriendLst.edit();
editor.putString(key, value.toString());
editor.commit();
}
public String LoadFriendList() {
MyApplication.FriendLst = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String FriendLsts = MyApplication.FriendLst.getString("Friends", "");
return FriendLsts;
}
Just Call this Code to get Your Json :-)
try {
JSONArray jarry1 = new JSONArray(LoadFriendList());
JSONObject jobject;
datamodelfriends.clear();
for (int i = 0; i < jarry1.length(); i++) {
jobject = jarry1.getJSONObject(i);
String FirstName = jobject.get("FirstName").toString();//You can get your own objects like this
datamodelfriends.add(new DataModelFriends(FirstName,...));
}
mAdapter = new CustomeAdapterFriendList(datamodelfriends, MainActivity.this);
RecyclerView_Friends.setAdapter(mAdapter);
} catch (Exception e) {
}

- 81
- 1
- 5
Yes. Values saved with SharedPreferences must be primitives or Strings. What form would the serialized JSON object take if not primitive or String (or Set)? JSON is a serialized data format. Use it, if that's what you've already got.

- 4,093
- 4
- 26
- 24