JAXB: How to always include xsi:type for elements of type that has subtypes?

394 Views Asked by At

Let's assume following schema:

<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>

Now when I serialize:

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

I got:

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

However when I serialize:

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

I got:

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

Is there a way to configure JAXB to include xsi:type in second example (despite being redundant)?

0

There are 0 best solutions below