在我的Android应用程序中,我使用Gson在SharedPreferences中保存/加载对象的数组列表。下面是我使用Gson编写的代码。
public static ArrayList<RequestModal> getModalList(Context ctx) {
Gson gson = new Gson();
String json = getSharedPreferences(ctx).getString("ModalList", new Gson().toJson(new ArrayList<>()));
Type type = new TypeToken<ArrayList<RequestModal>>() {}.getType();
return gson.fromJson(json, type);
}
在这里,"RequestModal“是包含一些字符串和整数的简单对象。它在“在线”的情况下工作得很好。但如果互联网是离线的,永远在下面的代码上工作。
Type type = new TypeToken<ArrayList<RequestModal>>() {}.getType();
我该怎么解决它呢?在使用/不使用Gson的情况下实现这样的功能的方法是什么?任何有好主意的人请帮助我。提前谢谢你。
发布于 2016-04-23 01:31:26
您可以在不使用Gson的情况下实现此功能:
public static EpisodeDetails parseEpisodeDetails(String content) {
EpisodeDetails episodeDetails = new EpisodeDetails();
try {
JSONObject jsonObject = new JSONObject(content);
episodeDetails.title = jsonObject.getString("title");
episodeDetails.subTitle = jsonObject.getString("subtitle");
episodeDetails.synopsis = jsonObject.getString("synopsis");
episodeDetails.ends_on = jsonObject.getString("ends_on");
JSONArray images = jsonObject.getJSONArray("image_urls");
if (images.length() > 0) {
episodeDetails.image_url = images.getString(0);
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return episodeDetails;
}
我所做的只是获取字符串,在你的例子中,是保存在共享前缀ModalList
中的字符串,然后将值插入到我的结构中,在我的代码中,结构被称为EpisodeDetails
,在你的代码中,对应的是RequestModal
。如果你不想通过代码来做这件事,并且想尝试另一个库,我推荐Jackson。
另一件事,在这行上:
String json = getSharedPreferences(ctx).getString("ModalList", new Gson().toJson(new ArrayList<>()));
您的第二个参数不是必需的。getString
将要加载的键作为第一个参数,将默认值作为第二个参数(在结果为空的情况下)。您可以将其更改为""
或null
。
发布于 2016-04-23 01:55:15
嗯,你的问题的另一个解决方案可能是TinyDB。它利用Gson
将对象的ArrayLists
保存在sharedPrefs
中,其使用方法非常简单:
Person person = new Person("john", 24);
tinydb.putObject("user1", person);
ArrayList<Person> usersWhoWon = new ArrayList<Person>();
tinydb.putListObject("allWinners", usersWhoWon);
就是这样,查看我上面给出的链接来查看使用细节。
https://stackoverflow.com/questions/36799316
复制相似问题