2011-11-17 87 views
7

如何返回XML或JSON中的Question对象列表?使用JAX-RS返回对象列表

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

我得到这个异常:

严重:映射的异常反应:500(内部服务器错误) javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException :为Java 类java.util.Vector,和Java类型 java.util.List的,和MIME媒体消息正文作家 类型的应用/八位字节流没有被发现

回答

4

尝试:

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

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

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

编辑 增加原创的答案以上

+0

似乎不有所作为:( – LuckyLuke

+0

见编辑,只是出于兴趣,你使用? – Thys

+2

我没有添加对域类的@XmlRootElement注释什么版本的JAX是,现在的作品。它确实与你一起工作,然后第一个例子:) – LuckyLuke

0

您的Web服务可能会是这样:

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

,那么你应该创建一个提供者,MessageBodyWriter:

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

} 
6

在我的情况下,同样的问题被加入POJOMappingFeature初始参数的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> 

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

3

首先,您应该设置适当的@Produces注释。 第二,你可以使用GenericEntity序列化一个列表。

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