使用JAX-RS时返回对象列表

Luc*_*uke 8 java ejb jax-rs java-ee

如何以XML或JSON格式返回Question对象列表?

@Path("all")
@GET
public List<Question> getAllQuestions() {
    return questionDAO.getAllQuestions();
}
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

SEVERE:响应的映射异常:500(内部服务器错误)javax.ws.rs.WebApplicationException:com.sun.jersey.api.MessageException:Java类java.util.Vector的消息体编写器和Java类型java.util找不到.List和MIME媒体类型application/octet-stream

Thy*_*hys 7

尝试:

@Path("all")
@GET
public ArrayList<Question> getAllQuestions() {
    return (ArrayList<Question>)questionDAO.getAllQuestions();
}
Run Code Online (Sandbox Code Playgroud)

如果您的目标是返回可以使用的项目列表:

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

编辑 上面添加了原始答案

  • 我没有在域类上添加@XMLRootElement注释,现在它可以正常工作.它确实与你合作第一个例子然后:) (2认同)

Kri*_*zsa 6

我的案例中的同样问题是通过将POJOMappingFeature init param添加到REST servlet来解决的,所以它看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

现在它甚至可以在Weblogic 12c上返回List.