【发布时间】:2020-04-16 23:54:59
【问题描述】:
所以我有这门课
public class Place {
ArrayList<Stop> stops;
String name;
Location location;
public Place(String name, Location location){
this.name = name;
this.location = location;
}
public void addStop(Stop stop){
this.stops.add(stop);
}
public Location getLocation() {
return location;
}
public String toString(){
return name+ " : " +location.toString();
}
}
我用于 Android 项目。每个 Place 对象都有一个 Location 对象(来自 Google Play Services),应用程序有一个 ArrayList items 数组列表,用于存储用户输入数据。我正在使用 Gson 序列化该 ArrayList 并将其保存到 SharedPrefs,但是当我恢复数据时,来自 Location 对象的所有参数都会出现 null。这是我的代码:
//If user has defined places, load them from storage
mPrefs = getActivity().getPreferences(MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("user_places", "");
Type placeListType = new TypeToken<ArrayList<Place>>(){}.getType();
if(json.length() > 0) items = gson.fromJson(json, placeListType);
else items = new ArrayList<Place>();
...
//Saves user data for future use
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
prefsEditor.putString("user_places", json);
prefsEditor.apply();
我做错了什么?如何确保正确还原原始 Location 对象?
【问题讨论】:
-
1、2 或 1000 个地点和/或站点是否也会发生这种情况?
-
您能否显示序列化后收到的
JSON? -
我最终改变了
Place的结构。它没有Location对象,它只存储初始Location对象的经度/纬度坐标,应用程序在反序列化时对其进行重构。当我测试 GSON 返回的JSON字符串时,我注意到Location对象中只有一个参数被序列化(Location被记录的时间)。所以这可能是序列化而不是反序列化的问题
标签: java android serialization gson sharedpreferences