简体   繁体   中英

Return a list of objects when using JAX-RS

How can I return a list of Question objects in XML or JSON?

@Path("all")
@GET
public List<Question> getAllQuestions() {
    return questionDAO.getAllQuestions();
}

I get this 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.Vector, and Java type java.util.List, and MIME media type application/octet-stream was not found

Try:

@Path("all")
@GET
public ArrayList<Question> getAllQuestions() {
    return (ArrayList<Question>)questionDAO.getAllQuestions();
}

If your goal is to return a list of item you can use:

@Path("all")
@GET
public Question[] getAllQuestions() {
    return questionDAO.getAllQuestions().toArray(new Question[]{});
}

Edit Added original answer above

The same problem in my case was solved by adding the POJOMappingFeature init param to the REST servlet, so it looks like this:

<servlet>
    <servlet-name>RestServlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

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

Now it even works with returning List on Weblogic 12c.

First of all, you should set proper @Produces annotation. And second, you can use GenericEntity to serialize a list.

@GET
@Path("/questions")
@Produces({MediaType.APPLICAtION_XML, MediaType.APPLICATION_JSON})
public Response read() {

    final List<Question> list; // get some

    final GenericEntity<List<Question>> entity
        = new GenericEntity<List<Question>>() {};

    return Response.ok(entity).build();
}

Your webservice may look like this:

@GET
@Path("all")
@Produces({ "application/xml", "application/*+xml", "text/xml" })
public Response getAllQuestions(){
 List<Question> responseEntity = ...;
 return Response.ok().entity(responseEntity).build();
}

then you should create a Provider, MessageBodyWriter:

@Produces({ "application/xml", "application/*+xml", "text/xml" })
@Provider
public class XMLWriter implements MessageBodyWriter<Source>{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM