![](/img/trans.png)
[英]Using ArrayFixture with a list of objects containing nested non-primitive objects
[英]Using Gson to serialize ArrayList of objects with non-primitive values?
所以我有这门课
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 服务),应用程序有一个 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 对象?
如果我正确理解了您的问题,那可能是因为您正在从 2 个不同的活动中加载和保存您的 Json 字符串。
SharedPreferences mPrefs = getActivity().getPreferences(MODE_PRIVATE);
getPreferences() 方法仅在您访问同一活动中的值时才有效。
如果您想将您的值保存到活动 A 中的 SharedPreferences,并稍后在活动 B 中获取它们,请尝试使用以下代码:
SharedPreferences mPrefs = getSharedPreferences("MySharedPreferences", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
prefsEditor.putString("user_places", json);
prefsEditor.apply();
然后像这样访问它们:
SharedPreferences mPrefs = getActivity().getPreferences(MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("user_places", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.