Search code examples
javaxmlmappingdozerxsitype

How to map an xml, which uses xsi:type with dozer?


I have an xml, which uses an xsi:type attribute, so the "BaseData" element can contain "ChildField" element in spite of the "ChildField" element is not the member of "BaseData" element in the schema:

<BaseData xsi:type="Child">
    <ChildField>value</ChildField>
</BaseData>

The generated java code is:

Child:

@XmlSeeAlso({
    Child.class,
})
public class BaseData {}

Base:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Child", propOrder = {
    "childField"
})
public class Child extends BaseData
{
    @XmlElement(name = "ChildField")
    protected String childField;
}

Now finally, I want this structure map to my structure, but when I put this in dozer mapping xml file, it fails:

<field>
    <a>baseData</a>
    <b>myData</b>
    <a-hint>BaseData,Child</a-hint>
    <b-hint>MyClass</b-hint>
</field>

<field>
    <a>baseData.childField</a>
    <b>myData.myField</b>
</field>

The exception I get is:

org.dozer.MappingException: No read or write method found for field (baseData.childField) in class (class BaseData)

I use

mapper.map

method


Solution

  • I solved this issue by creating a custom converter which converts the BaseClass to MyClass. It first tries to cast BaseClass instance to ChildClass. If successful then it passes the field values to MyClass instance.