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;
    }

}

and service:

@Path("/test")
public class Service {

    @GET
    @Produces({MediaType.APPLICATION_JSON })
    public List<Todo> getAllGadgets() {
        return Arrays.asList(new Todo[] { new Todo() });
    }

}

my 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>

All this work if I set MediaType.APPLICATION_XML for Produces annotation. But for JSON I get the following exception:

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

I use Jersey 1.6 and, according to the tutorial, JSON format should work with JAXB without any additional programming. What's wrong?


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)


将以下参数添加到web.xml文件中的球衣小服务程序中,这是jersey-servlet的最新1.x版本所必需的。

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

I use Google App Engine and have struggled a lot with this also, if you use jersey-bundle-1.17.jar most of the stuff work until you add

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

you will get a lot of strange messages. This is because you miss some jackson jars. If you go to jersey homepage and download the zip and the bundle. Just drop the bundle and from the zip you need to add the 4 jackson jars in your classpath and you should get everything working without any error.

Adding jackson-jaxrs-1.9.2.jar solve this error below

SEVERE: The registered message body writers compatible with the MIME media type are:
application/json ->

Adding jackson-xc-1.9.2.jar solve this warrning below

java.lang.NoClassDefFoundError: org/codehaus/jackson/xc/JaxbAnnotationIntrospector

I hope this helps somebody.

链接地址: http://www.djcxy.com/p/45570.html

上一篇: Jersey / Atmosphere不能生成JSON

下一篇: 如何使用JAXB为Jersey 1.6生成JSON输出