Return a list of objects when using JAX-RS

35,141

Solution 1

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

Solution 2

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.

Solution 3

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>>(list) {};

    return Response.ok(entity).build();
}
Share:
35,141
LuckyLuke
Author by

LuckyLuke

Updated on July 09, 2022

Comments

  • LuckyLuke
    LuckyLuke almost 2 years

    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

  • LuckyLuke
    LuckyLuke over 12 years
    does not seem to make a difference:(
  • Thizzer
    Thizzer over 12 years
    See edit, just out of interest, what version of JAX are you using?
  • LuckyLuke
    LuckyLuke over 12 years
    I had not added the @XMLRootElement annotation on the domain class, now it works. It did work with you first example then:)
  • thisisananth
    thisisananth about 12 years
    Are the questions returned for getAllQuestions() just strings or Objects ? If it is objects are they displayed as XML? Can you post a sample response?
  • Thizzer
    Thizzer about 12 years
    They are objects and being displayed as JSON.