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

标签 android json jackson

我的 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/

相关文章:

android - 上传到 Alpha channel 的新错误 : The apk has permissions that require a privacy policy set for the app: GET_ACCOUNTS

android - 找不到类 'org.codehaus.jackson.map.ObjectMapper'?

android - Android中查询、备份、删除、插入联系人

android - 使用时间轴和 lambda 表达式的定期处理不适用于 Javafx8 for android (gluon)

java - Android Studio 错误 : "Environment variable does not point to a valid JVM installation"

html - Json 服务以 HTML 形式返回

ruby-on-rails - json Errno::EPERM 不允许操作

javascript - 从 JSON 对象中减去数组 JavaScript

java - Jackson:将 JSON 转换为对象:ArrayList of objects with arraylist of objects with arraylist of objects

java - Jackson:不同的 XML 和 JSON 格式