如何使用JAXB使用Jersey 1.6生成JSON输出 [英] How to produce JSON output with Jersey 1.6 using JAXB
问题描述
@XmlRootElement
public class Todo {
private String s = "test";
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
和服务:
@Path("/test")
public class Service {
@GET
@Produces({MediaType.APPLICATION_JSON })
public List<Todo> getAllGadgets() {
return Arrays.asList(new Todo[] { new Todo() });
}
}
我的web.xml:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.test</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
如果我为Produces注释设置MediaType.APPLICATION_XML,那么这一切都有效。但对于JSON,我得到以下异常:
All this work if I set MediaType.APPLICATION_XML for Produces annotation. But for JSON I get the following exception:
SEVERE:响应的映射异常:
500(内部服务器错误)
javax.ws.rs.WebApplicationException:
com.sun.jersey.api.MessageException:用于Java类的
消息正文编写器
java.util.Arrays $ ArrayList和Java
类型java.util.List,
和MIME媒体类型应用程序/ json
未找到
SEVERE: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.Arrays$ArrayList, and Java type java.util.List, and MIME media type application/json was not found
我使用Jersey 1.6,根据教程,JSON格式应该可以与JAXB一起使用而无需任何额外的编程。怎么了?
I use Jersey 1.6 and, according to the tutorial, JSON format should work with JAXB without any additional programming. What's wrong?
推荐答案
我解决了这个问题。我需要做的就是将jersey-json-1.6.jar库添加到项目中(这不是球衣的一部分)
I solved this. All I needed to do was to add jersey-json-1.6.jar library to the project (this is not required part of jersey)
这篇关于如何使用JAXB使用Jersey 1.6生成JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!