1
votes

I want to annotate a field in my jaxb generated class with this annotation - @XmlElement(required = false). Which attribute in the XSD would generate my field with this annotation?. I can't hand type this as the JAXB classes are auto generated using Maven every time a build is run.

My jaxb version is xjc 2.2.4-2

Thanks

1
My requirement is to make the field optional. I understand that if I declare the field to be micOccurs=0 in the XSD it would do the job. But when I did so, xjc is not adding the @XmlElement(required = false) annotation by default to the field in the jaxb class.Ganga Aloori
Another interesting observation is that when I hand type the annotation to the field in the jaxb class and use JDK's schemagen to tool to generate the schema from jaxb classes, I see that the field is added with minOccurs=0 attribute in the generated schemaGanga Aloori

1 Answers

1
votes

When an element has minOccurs="0" the corresponding @XmlElement has required=false. Note that false is the default value of the required attribute so it may not actually appear in the generated annotation.


UPDATE

Based on your comment:

Let me explain my actual problem. I'm using Jackson to generate the JSON from the JAXB classes. Issue is when the element is not present in the xml, I see the json output with the field name as 'pip' and value as null. I am actually expecting the field 'pip' to be absent from my json output as I declared it to be minOccurs=0 in the XSD. Can't figure out if it's an issue with JAXB or Jackson. Interestingly when I annotate the field explicitly with required=false in the jaxb class, I see my expected output with the field being absent

This is an issue with Jackson not handling the default value of the required property on the @XmlElement annotation correctly.