在Gson中使用SharedPreferences



我有问题加载数据从SharedPreferencesGson。我有ArrayListsProduct类对象。我想保存它们,然后加载它们。下面是我的loadList方法:

public void loadList(ArrayList list, String name){
SharedPreferences sharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(name, null);
Type type = new TypeToken<ArrayList<Product>>() {}.getType();
list = gson.fromJson(json, type);
//Toast.makeText(this, ""+list.size(), Toast.LENGTH_SHORT).show();
if(list == null){
list = new ArrayList<>();
}
}

当我使用这个不带参数的方法时,一切正常。但是当我尝试将ArrayList作为参数发送时,它不起作用并且列表被强调。

假设有一个Json文件:

[
{
"name": "product1",
"itemNumber": "123"
},
{
"name": "product2",
"itemNumber": "456"
}
]

解析json需要一个模型类,这里是Product:

data class Product(val name: String, val itemNumber: String)

在这个例子中,我在资产文件夹中保留了预定义的json文件,但在你的情况下,你正在从SharedPreference中读取它。我认为这就是问题的根源。因为成功读取json后,我能够在所需的列表中解析json。

你可以参考下面的方法,它可以给你一些解析的想法。

void parseGson() {
String json = null;
try {
InputStream is = getAssets().open("input.json"); //file name placed in assets folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
Type type = new TypeToken<ArrayList<Product>>() {}.getType();
List<Product> list = new Gson().fromJson(json, type);
System.out.println(list);
}

输出:

I/System.out: [Product(name=product1, itemNumber=123), Product(name=product2, itemNumber=456)]

如果你需要更多的帮助,你需要提供json文本和产品模型的代码。我希望它能帮助你解决你的问题。