Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is @XmlElement necessary for Jaxb

My question is, whether it is necessary to add @XmlElement before each element in your pojo to be picked up by jaxb, when making a JSON response. I am using jersey-json 1.17 . The reason I ask this is because, the example given on Jersey site does not use the annotation.

I get an out put as {}, but when I add @XmlElement before the attributes, I get the expected JSON output. Am I doing something wrong, because of which my JSON string is empty ?

My code :

The vertices list is populated in the constructor.

This produces the wrong output of {}

@XmlRootElement
public class SquareModel {
    List<Float> vertices = new ArrayList<Float>();
    ....
}

Whereas this produces the a correct JSON string :

@XmlRootElement
public class SquareModel {
    @XmlElement(name="vertices")
    List<Float> vertices = new ArrayList<Float>();
    ....
}

My resource class which returns the JSON

@GET
@Produces(MediaType.APPLICATION_JSON)
public SquareModel getJsonString() {
    return new SquareModel();
}

Thanks :)

like image 804
Amol Avatar asked Jan 31 '26 04:01

Amol


1 Answers

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).

  • http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html

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

  • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
like image 170
bdoughan Avatar answered Feb 02 '26 19:02

bdoughan