保存自定义对象数组来共享preferences自定义、数组、对象、preferences

2023-09-06 13:52:20 作者:衬哽

我可以将我自己的对象数组保存到共享preferences,像下面的帖子?

Can I save my own object array to the SharedPreferences, like in the post below?

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。您可以立即下载这个罐子从这里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);