Jackson fastxml 根据对象的根元素将对象列表反序列化为不同的对象

问题描述

我有以下 xml 文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<aRootElement key1="value1" key2="value2" key3="value3">
    <features>
        <aFeature name="a-value"/>
        <anotherFeature name="another-value" age="10"/>
    </features>
</aRootElement>

我需要将每个特征解析为一个同类对象。更具体地说:

我有

@JacksonXmlRootElement(localName = "aRootElement")
public class ARootElement {

    private String key1;
    private String key2;
    private String key3;

    private List<? extends Feature> features;


    @JsonCreator
    public ARootElement(@JacksonXmlProperty(localName = "key1") String key1,@JacksonXmlProperty(localName = "key2") String key2,@JacksonXmlProperty(localName = "key3") String key3,@JacksonXmlProperty(localName = "features") List<? extends Feature> features
    ) {
            [...]
    }

    //getters setter etc

@JacksonXmlRootElement(localName = "aFeature")
public class AFeature implements Feature {
    private String name;

    public AFeature(@JacksonXmlProperty(localName = "name") String name) {
            [...]
    }

    //getters setters
}

@JacksonXmlRootElement(localName = "anotherFeature")
public class AnotherFeature implements Feature {
    private String name;
    private String age;

    public AFeature(@JacksonXmlProperty(localName = "name") String name,@JacksonXmlProperty(localName = "age") String age) {
            [...]
    }
    
    //getters setters
}

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,visible = true,include = JsonTypeInfo.As.EXISTING_PROPERTY,defaultImpl = Void.class)
@JsonSubTypes({
        @JsonSubTypes.Type(value = AFeature.class,name = "aFeature"),@JsonSubTypes.Type(value = AnotherFeature.class,name = "anotherFeature")
})
public interface Feature {}

并且我需要 ARootElement 中的列表来包含两个对象。一个AFeature 类型,另一个AnotherFeature 类型。

目前 当我调用 XmlMapper::readValue 将 xml 作为字符串传递并将 valueType 作为 ARootElement.class 传递时,我得到一个包含空值的列表的 ARootElement。

您是否处理过类似的问题? 提前致谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)