Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 611
LuckyLuke Avatar asked Nov 17 '11 10:11

LuckyLuke


People also ask

What can a JAX-RS method return?

If the URI path template variable cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 400 (“Bad Request”) error to the client. If the @PathParam annotation cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 404 (“Not Found”) error to the client.

What is the use of @delete annotation of JAX-RS?

The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests. The behavior of a resource is determined by the HTTP method to which the resource is responding.

What is the difference between JAX-RS and JAX WS?

Actually,JAX-WS represents both RESTful and SOAP based web services. One way to think about it is that JAX-RS specializes in RESTful, while JAX-WS allows you more flexibility to choose between either, while at the same time being (in some cases) more complicated to configure. Thank you for simple explanation.


2 Answers

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

like image 106
Thizzer Avatar answered Sep 19 '22 09:09

Thizzer


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.

like image 42
Kristof Jozsa Avatar answered Sep 19 '22 09:09

Kristof Jozsa