gpt4 book ai didi

java - Android - JSON 存储列表包含在应用程序退出、重新打开时恢复为父类(super class)的对象

转载 作者:太空狗 更新时间:2023-10-29 15:12:18 27 4
gpt4 key购买 nike

我有一个 ArrayList <GeneralTemplate> items

在我的整个程序中,我添加了例程,它们是 GeneralTemplate 的子类,即 items.add(new Routine("Test"));一切都很好。

最重要的是,我可以执行以下操作.. Routine myRoutine = items.get(position);

我使用 Google 的 GSON 库将这一大项目列表保存在 JSON 格式的特殊数据对象中。我相信这可能是问题所在。

此数据对象包含 ArrayList <GeneralTemplate> items .在我的程序中,我可以看到项目列表中存储的例程确实是 Routine对象。然后我使用下面的代码保存它。我在调试器中遵循了这个过程,当我设置 RoutineList 时,Routine 对象得到维护没有问题。

// Global save String method
public static void save()
{
Editor editor = sharedPreferences.edit();

RoutineData tempSaveObject = new RoutineData();
tempSaveObject.setRoutineList(routineList);

String routineListInJSON = gson.toJson(tempSaveObject);

editor.putString(ROUTINE_LIST, routineListInJSON).commit();
}

当我重新启动应用程序并检索数据时出现问题。列表中的所有项目恢复为 GeneralTemplate对象,不能转换回 Routine通过Routine routine = (Routine) items.get(position) -> ClassCastException (加载代码如下)

    // Get a global sharedPreferences object that can be used amongst Activities
sharedPreferences = this.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);

if (sharedPreferences.contains(ROUTINE_LIST))
{
String routineListJSON = sharedPreferences.getString(ROUTINE_LIST, null);
routineDataObject = gson.fromJson(routineListJSON, RoutineData.class);

routineList = routineDataObject.getRoutineList();
}
else
{
routineList = new ArrayList<GeneralTemplate>();
}

因此,我无法访问特定的方法和变量,因为我无法重新获得子类上下文。这个问题还有其他几个例子,所以如果你们有什么好的解决方案,那将会很有帮助。

谢谢!

排序:

Genson JSON 库。

https://code.google.com/p/genson/downloads/detail?name=genson-0.94.jar&can=2&q=

让事情变得如此简单,无需自定义序列化器/反序列化器。默认处理所有深度多态性问题。

如 Eugen 的回答所示实现

最佳答案

这是因为您有一个 GeneralTemplate 列表,而序列化 Gson 知道列表中每个元素的具体类型,但在反序列化期间 Gson 不知道要反序列化为哪种类型(因为它是一个列表通用模板)。

我不确定,但看起来他们有一些贡献(不是 Gson 的一部分)允许在序列化流中添加类型信息,这允许 Gson 反序列化回正确的类型。

您也可以试试 Genson库,开箱即用地支持处理多态类型。它具有 Gson 和其他一些人提供的功能。以下是实现它的方法:

// first configure your Genson instance to enable polymorphic types support and  
// serialization based on concrete types
Genson genson = new Genson.Builder()
.setWithClassMetadata(true)
.setUseRuntimeTypeForSerialization(true)
.create();

// and now just use it to serialize/deser
String json = genson.serialize(routineData);
RoutineData data = genson.deserialize(json, RoutineData.class);

编辑问题解决了。 Routine 类没有默认构造函数。将 @JsonProperty("name") 放在 ctr 参数上并使用 gensons 以前的配置解决了这个问题。

关于java - Android - JSON 存储列表包含在应用程序退出、重新打开时恢复为父类(super class)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com