【问题标题】:How to return an arraylist as response to the restful cxf webservice call如何返回一个arraylist作为对restful cxf webservice调用的响应
【发布时间】:2016-06-10 06:26:15
【问题描述】:
我正在尝试使用 restful cxf webservice 调用从 MongoDB 检索文档列表。但我正面临
在类 ArrayList 中没有找到响应的消息正文编写器。
我关注了this tutorial。在这里,他们在 CxfRestServiceImpl 类中返回员工对象作为响应。所以他们使用了@XMLElement(name = 'employee')。
但现在我试图从 MongoDB 返回文档列表作为CxfRestServiceImpl 类中的响应。为了克服此错误,我需要做哪些更改?
【问题讨论】:
标签:
java
web-services
rest
arraylist
cxf
【解决方案1】:
如果我理解你的正确,你的代码中有这个异常。比,你最好将你的 List 答案包装在其他类中。
@XmlRootElement(name="DocumentList")
public class DocumentList {
@XmlElement
public List<Document> documentList;
}
【解决方案2】:
你可以像这样“包装”到数组中
return Response.status(Response.Status.OK).entity(yourList.toArray(new YourObject[yourList.size()])).build();
其中 yourList 是 List<yourObject> 或 ArrayList<yourObject>
【解决方案3】:
您可以返回服务中的对象列表。 JAXB 将从 ArrayList 进行转换
@GET
@Path("/employees")
public List<Employee> getEmployees()
确保对象具有 JAXB XmlRootElement 注释。
@XmlRootElement(name="Employee")
public class Employee{
}