Is @XmlElement necessary for Jaxb Is @XmlElement necessary for Jaxb json json

Is @XmlElement necessary for Jaxb


No, by default a JAXB (JSR-22@) implementation will treat all public fields and properties (get/set combinations) as mapped (not requiring the @XmlElement annotation).

If you wish to annotate a field I would recommend annotating your class with @XmlAccessorType(XmlAccessType.FIELD)


According to this http://jersey.java.net/nonav/documentation/latest/json.html#json.jaxb.approach.sectionYou should have this annotation (I'm also using it in my code, even though it XML oriented, but it gives me cool JSON also)

Taking this approach will save you a lot of time, if you want to easily produce/consume both JSON and XML data format. Because even then you will still be able to use a unified Java model. Another advantage is simplicity of working with such a model, as JAXB leverages annotated POJOs and these could be handled as simple Java beans.

A disadvantage of JAXB based approach could be if you need to work with a very specific JSON format. Then it could be difficult to find a proper way to get such a format produced and consumed. This is a reason why a lot of configuration options are provided, so that you can control how things get serialized out and deserialized back.

Following is a very simple example of how a JAXB bean could look like.

Example 5.3. Simple JAXB bean implementation

@XmlRootElement   public class MyJaxbBean {     public String name;     public int age;     public MyJaxbBean() {} // JAXB needs this     public MyJaxbBean(String name, int age) {       this.name = name;      this.age = age;    }  }