Reputation: 271
I am trying to implement a REST service using Spring 4.
The application is built using Java 7 and runs on Tomcat 7.
The REST method will return a customer object in JSON. The application is annotation-driven.
The Customer class has JAXB annotations. Jackson jars are present in the class path. As per my understanding Jackson will use JAXB annotations to generate the JSON.
The Customer Class :
@XmlRootElement(name = "customer")
public class Customer {
private int id;
private String name;
private List favBookList;
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "booklist")
@XmlElement(name="book")
public List getFavBookList() {
return favBookList;
}
public void setFavBookList(List favBookList) {
this.favBookList = favBookList;
}
}
I have annotated the REST service class as @RestController (as per Spring 4)
The REST method to return a customer object in JSON:
@RequestMapping(value="/customer.json",produces="application/json")
public Customer getCustomerInJSON(){
Customer customerObj = new Customer();
customerObj.setId(1);
customerObj.setName("Vijay");
ArrayList<String> favBookList = new ArrayList<String>();
favBookList.add("Book1");
favBookList.add("Book2");
customerObj.setFavBookList(favBookList);
return customerObj;
}
The result I expected, when I hit the URL :
{"id":1,"booklist":{"book":["Book1","Book2"]},"name":"Vijay"}
What I get:
{"id":1,"name":"Vijay","favBookList":["Book1","Book2"]}
It seems Jackson is ignoring the JAXB annotations @XmlElementWrapper(name = "booklist") and @XmlElement(name="book") above getFavBookList() method in Customer class
Am I missing something?
Need guidance. Thanks.
Upvotes: 1
Views: 2957
Reputation: 3831
Basically the point is, you have given xml annotations and are expecting Json output.
You need to find out Json equivalent for its xml counter part @xmlElementWrapper
.
This feature used to work in jackson 1.x but does not in Jackson 2.x
Upvotes: 1