Is it ok to save a JSON array in SharedPreferences?

前端 未结 9 2154
不知归路
不知归路 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: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>(){} .getType();
            ArrayList mUser = gson.fromJson(s, type);
    
        }
    

提交回复
热议问题