Is it ok to save a JSON array in SharedPreferences?

前端 未结 9 2097
不知归路
不知归路 2020-11-28 08:29

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 whe

相关标签:
9条回答
  • 2020-11-28 09:06

    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.

    0 讨论(0)
  • 2020-11-28 09:11

    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)

    0 讨论(0)
  • 2020-11-28 09:11

    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()
    
    0 讨论(0)
  • 2020-11-28 09:17

    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.

    0 讨论(0)
  • 2020-11-28 09:23

    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);
    
        }
    
    0 讨论(0)
  • 2020-11-28 09:24

    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.

    0 讨论(0)
提交回复
热议问题