Store objects in Android

前端 未结 2 1735
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 18:26

I would like to know what would be the best option to store a custom Java object that I have in my application. I\'ve read about serialization but it seems to be quite slow.

2条回答
  •  时光取名叫无心
    2020-12-16 18:52

    If you're not storing an over abundance of data you can use Gson to convert a Java object to a Json string and store the string in your app preferences. Gson has a toJson(obj) method and visa-vis.

    Getting data out of app preferences and into an object:

    String json = appSharedPrefs.getString("someName","");    
    return gson.fromJson(json, YourModel.class);
    

    To get data from your object into app preferences:

    String json = gson.toJson(obj);
    

    Then prefsEditor.putString("someName", json).apply().

提交回复
热议问题