Friday, January 9, 2009

RTFM or how to make it nullable with JAXB

This JAXB stuff is neat, except for those several use cases where is has to be learned by trial and error. Check this out.

I wanted to get my Flex client to access a web service. The client sent following XML as part of the SOAP message:

<price>
<costCategory xsi:nil="true"/>
<id>NaN</id>
<price>
...
</price>


Which got converted into an empty cost category instead of null.

Apparently, fixing it is simple - just make a property nillable. Ok, I annotated my POJO with @XmlElement thing:

@OneToOne
@XmlElement(nillable=true)
private CostCategory costCategory;

And that didn't work for some reason:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "costCategory"

Fix is simple annotate the getter instead:

@XmlElement(nillable=true)
public CostCategory getCostCategory() {
return costCategory;
}

Now it works like charm!