Home » Android » java – Is it ok to save a JSON array in SharedPreferences?

java – Is it ok to save a JSON array in SharedPreferences?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&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)

Answer:

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.

Answer:

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()

Answer:

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.

Answer:

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.

Answer:

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.

Answer:

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) {
                            }

Answer:

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);

    }