Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...