JAXB:如何始终包含具有子类型的类型的元素的xsi:type?

时间:2017-06-19 11:25:00

标签: java jaxb xsitype

让我们假设以下架构:

<xsd:complexType name="User">
    <xsd:sequence>
        <xsd:element name="name" type="xs:string"/>
    </xsd:sequence>
</xsd:complexType>
<xsd:complexType name="SpecialUser">
    <xsd:complexContent>
    <xsd:extension base="User">
        <xsd:sequence>
            <xsd:element name="speciality" type="xs:string"/>
        </xsd:sequence>
    </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="UserContainer">
    <xsd:sequence>
        <xsd:element name="user" type="User"/>
    </xsd:sequence>
</xsd:complexType>

现在我序列化了:

new UserContainer()
    .withUser(
        new SpecialUser()
            .withName("name")
            .withSpeciality("speciality")
    )

我得到了:

...
<user xsi:type="SpecialUser">
    <name>name</name>
    <speciality></speciality>
</user>
...

然而,当我序列化时:

new UserContainer()
    .withUser(
        new User()
            .withName("name")
    )

我得到了:

...
<user>
    <name>name</name>
</user>
...

有没有办法在第二个例子中配置JAXB以包含xsi:type(尽管是多余的)?

0 个答案:

没有答案