Jackson XML - 反序列化空类和多态

时间:2015-11-15 17:04:56

标签: java xml jackson polymorphism deserialization

我有以下界面:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
        @JsonSubTypes.Type(value = EmptyProxy.class, name = "empty"),
        ... other types not included ...
})
public interface Proxy {
}

我有以下实现:

@JsonTypeName("empty")
public static class EmptyProxy implements Proxy {
}

如你所见,它只是一个空洞。我离开了这个例子中的其他(工作)实现。

我有以下容器数据类:

public static class Data {
    @JacksonXmlProperty(localName = "name")
    private String name;
    @JacksonXmlProperty(localName = "proxy")
    private Proxy  proxy;
}

反序列化EmptyProxy似乎不起作用。例如:

final ObjectMapper mapper = new XmlMapper().registerModule(new JacksonXmlModule());
final Data data = mapper.readValue("<data><name>my-name</name><proxy><empty/></proxy></data>", Data.class);

这给出了以下例外:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of Test$EmptyProxy out of VALUE_NULL token
 at [Source: java.io.StringReader@59ec2012; line: 1, column: 42] (through reference chain: Data["proxy"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:857)

这是杰克逊的错误吗? FWIW,当我向EmptyProxy添加虚拟字段时,它可以正常工作。

更新

我只尝试使用JAXB,并获得相同的结果。代码:

public static class Data {
    @XmlElement(name = "name")
    private String name;
    @XmlElements({
            @XmlElement(type = EmptyProxy.class, name = "empty")
    })
    private Proxy  proxy;
}

public interface Proxy {
}

@XmlType(name = "empty")
public static class EmptyProxy implements Proxy {
}

public static void main(String[] a) throws IOException {
    final ObjectMapper mapper = new XmlMapper()/*.registerModule(new JacksonXmlModule())*/.registerModule(new JaxbAnnotationModule());
    final Data data = mapper.readValue("<data><name>my-name</name><proxy><empty></empty></proxy></data>", Data.class);
}

1 个答案:

答案 0 :(得分:0)

我为此创建了一个错误条目。请参阅http://github.com/FasterXML/jackson-dataformat-xml/issues/169