Is it ok to save a JSON array in SharedPreferences?

前端 未结 9 2098
不知归路
不知归路 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:25

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

    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.

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

    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()
    
    }
    
    0 讨论(0)
提交回复
热议问题