3

当我将 @XmlSeeAlso 注释添加到抽象 xsd 类时,原始 JAXB Marshaller 工作正常。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Service xmlns="http://www.a.com">
    <animal xsi:type="Dog" holder="Apache" name="Tomcat" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</Service>

当我转向jackson(注册了JaxbAnnotationModule)时,我得到了一个不同的序列化字符串,其“xsi:type”标签丢失了。

<Service xmlns="">
    <animal holder="Apache" name="Tomcat"></animal>
</Service>

我已经尝试过 @JsonTypeInfo 注释,但它不起作用。如何修复这是我的示例 xsd 实体,

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"animal"})
@XmlRootElement(name = "Service")
public class Service {

    @XmlElement(name = "animal")
    private Animal animal;

    public Animal getAnimal() {
        return animal;
    }

    public void setAnimal(Animal animal) {
        this.animal = animal;
    }
}


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Animal", propOrder = {"name"})
@XmlSeeAlso({Dog.class})
public abstract class Animal {

    @XmlAttribute(name = "name", required = true)
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Dog", propOrder = {"holder"})
public class Dog extends Animal {

    @XmlAttribute(name = "holder", required = true)
    private String holder;

    public String getHolder() {
        return holder;
    }

    public void setHolder(String holder) {
        this.holder = holder;
    }
}

测试用例,

@Test
public void testXsiType() throws Exception {
    Service service = new Service();
    Dog dog = new Dog();
    service.setAnimal(dog);
    dog.setName("Tomcat");
    dog.setHolder("Apache");

    JAXBContext jaxb = JAXBContext.newInstance(Service.class, Dog.class);
    Marshaller marshaller = jaxb.createMarshaller();
    StringWriter writer = new StringWriter();
    marshaller.marshal(service, writer);
    System.out.println(writer.toString());

    ObjectMapper serializer = new XmlMapper();
    serializer.registerModule(new JaxbAnnotationModule());
    serializer.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    serializer.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);

    System.out.println(serializer.writeValueAsString(service));

}

我使用的库,

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.4.5</version>
</dependency>
4

0 回答 0