How to produce JSON output with Jersey 1.6 using JAXB

Mikhail picture Mikhail · May 17, 2011 · Viewed 36k times · Source
@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?

Answer

Mikhail picture Mikhail · May 17, 2011

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)