我使用 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/