gpt4 book ai didi

android - JsonSubTypes,多态对象列表和 Parcelable

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:48:14 25 4
gpt4 key购买 nike

我的 JSON 结构:

{  
...
"type":"post", // Type could vary
"items":[] // Array of items, each item is typeOf("type")
...
}

我如何在我的 POJO 中反序列化和正确打包 items 列表:

public class ItemsEnvelope {
private String type;

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "type",
visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = A.class, name = "A"),
@JsonSubTypes.Type(value = B.class, name = "B"),
@JsonSubTypes.Type(value = C.class, name = "C")
})
private List<Item> items;

interface Item extends Parcelable {}

class A implements Item {
// Bunch of getters/setters and Parcelable methods/constructor
}

class B implements Item {
// Bunch of getters/setters and Parcelable methods/constructor
}

class C implements Item {
// Bunch of getters/setters and Parcelable methods/constructor
}

// Bunch of getters/setters and Parcelable methods/constructor
}

要打包类型化列表,应该提供一个 CREATOR 对象,而接口(interface)显然不能提供该对象。我应该使用抽象类而不是接口(interface)吗?

最佳答案

首先要注意的是:EXTERNAL_PROPERTY 只有在值包含在另一个对象 (POJO) 中时才有效;不适用于 List、数组或 Map

如果您使用的是其他包含方法之一,那么应该可以将内容序列化为 JSON,并按预期读取生成的 JSON 返回保留类型。也就是说,从 Java 对象开始时支持往返序列化。除此之外,还可以支持一些JSON编码结构;但这取决于您要支持的确切结构类型。

关于android - JsonSubTypes,多态对象列表和 Parcelable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31638418/

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