保存自定义对象数组来共享preferences [英] Save custom object array to Shared Preferences
问题描述
我可以将我自己的对象数组保存到共享preferences,像下面的帖子?
Can I save my own object array to the SharedPreferences, like in the post below?
<一个href="http://stackoverflow.com/questions/14981233/android-arraylist-of-custom-objects-save-to-shared$p$pferences-serializable">Android自定义对象的ArrayList - 保存到共享preferences - ?序列化
不过,他并没有保存一个数组,所以有可能保存自定义对象的数组来共享preferences样的联系?
But there he doesn't save an array, so is there a possibility to save a custom object array to SharedPreferences like in the post of the link?
推荐答案
您可以使用GSON序列化类的对象,并将其存储到共享preferences。您可以立即下载这个罐子从这里<一个href="https://$c$c.google.com/p/google-gson/downloads/list">https://$c$c.google.com/p/google-gson/downloads/list
You can use gson to serialize class objects and store them into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
要保存:
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
中检索:
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
这篇关于保存自定义对象数组来共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!