android - Kotlin:如何在 SharedPreferences 中保存数组列表

标签 android kotlin sharedpreferences moshi

我使用 kotlin 创建了一个 Android 应用程序,在这个应用程序中我使用提供所有产品列表的 WS。那么,如何使用 moshi 库将产品列表保存在 SharedPreferences 中? 这是我的代码:

fun setArrayDataBykeyValue(context: Context, key: String, DataArrayList: Array<ProductData>) {
    val gson = Gson()
    val jsonString = gson.toJson(DataArrayList)
    val sp = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
    sp.edit().putString(key, jsonString).commit()
}

最佳答案

以下是具体操作方法。

Moshi moshi = new Moshi.Builder().build();
Type type = Types.newParameterizedType(List.class, Person.class);
JsonAdapter< List > jsonAdapter = moshi.adapter(type);
String json = jsonAdapter.toJson(body.getParams());

其中 Person 是您的 POJO 或某个模型类。

然后将此字符串保存在共享首选项中,并执行相反的操作以返回列表

List<Person> persons = jsonAdapter.fromJson(json);

关于android - Kotlin:如何在 SharedPreferences 中保存数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56868579/

相关文章:

android - 将 R 文件与导致 ClassCastException 的代码同步

android - Unresolved reference : junit4: Android ComposeUI testing

ios - Flutter:未处理的异常:MissingPluginException(未在 channel plugins.flutter.io/shared_preferences 上找到方法 getAll 的实现)

更改 Activity 时 Android 沉浸式模式重置

android - 在更新程序脚本中使用通配符删除文件

android - 如何确保 Android 中的数字十进制键盘?

kotlin - 在 Kotlin 中满足条件时重新分配变量值的最简洁方法

字符串模板中的可空变量

Android:PreferenceFragment 只显示第一偏好

android - 带有共享首选项名称的 ListView 并将它们链接起来