Search code examples
jaxbjaxb2

jaxb mapping complex type with one value to a String


I have somehow a tricky situation here. On one hand I need to be in sync with this xsd scheme on the other hand the generated classes from this xsd is somehow useless.

<xs:schema>
    ...
    <xs:complexType name="Text">
        <xs:simpleContent>
            <xs:extension base="xs:string"/>
        </xs:simpleContent>
    </xs:complexType>
</xs:schema>

My generated Class from the above xsd is this.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Text", propOrder = { "value" })
public class Text {
    @XmlValue
    protected String value; 
    .. getter .. setter
}

The class has only one string property and it would make sense to replace it with the String type instead of the Class.

Question: How can I skip the Text Class and use String instead but preserve the existing xsd.

So instead of writing this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Description", propOrder = { "content" })
public class Description{
  @XmlElement(name = "Content") 
  protected Text content;

I want to write something like this:

@XmlElement(name = "Content")   
@MagicHere_ThisTypeMappToText
protected String content;

Is there an Annotation in jaxb that allows me to wrap the text class but preserves to be valid with the xsd?


Solution

  • Usually if you want to map one class to a different class in object (de)-serialization an XmlAdapter implementation is the best choice.

    In your case an TextAdapter extends XmlAdapter<Text, String> {..} should do the trick. You can explicitly assign the adapter to one field using the @XmlJavaTypeAdapter(TextAdapter.class) annotation.