首页 文章

使用JAXB注释,Jackson和Spring生成JSON

提问于
浏览
1

我正在尝试使用Spring 4实现REST服务 .

该应用程序使用Java 7构建,并在Tomcat 7上运行 .

REST方法将返回JSON中的客户对象 . 该应用程序是注释驱动的 .

Customer类具有JAXB注释 . Jackson 的 jar 出现在阶级路径中 . 根据我的理解,Jackson将使用JAXB注释生成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;
}
}

我已将REST服务类注释为@RestController(根据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"]}

Jackson 似乎忽略了Customer类中的JAXB注释 @XmlElementWrapper(name = "booklist")@XmlElement(name="book") 以上的getFavBookList()方法

我错过了什么吗?

需要指导 . 谢谢 .

1 回答

  • 1

    基本上,重点是,您已经给出了xml注释并且期望Json输出 .

    你需要找到它的xml计数器部分 @xmlElementWrapper 的Json等价物 .

    此功能曾用于jackson 1.x,但不适用于Jackson 2.x.

相关问题