返回响应对象时如何自动序列化集合

返回响应对象时如何自动序列化集合

本文介绍了JAX-RS:返回响应对象时如何自动序列化集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 JAXB 注释的员工类:

I have a JAXB-annotated employee class:

@XmlRootElement(name = "employee")
public class Employee {

    private Integer id;
    private String name;

    ...

    @XmlElement(name = "id")
    public int getId() {
        return this.id;
    }

    ... // setters and getters for name, equals, hashCode, toString
}

还有一个 JAX-RS 资源对象(我使用的是 Jersey 1.12)

And a JAX-RS resource object (I'm using Jersey 1.12)

@GET
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/")
public List<Employee> findEmployees(
    @QueryParam("name") String name,
    @QueryParam("page") String pageNumber,
    @QueryParam("pageSize") String pageSize) {
    ...
    List<Employee> employees = employeeService.findEmployees(...);

    return employees;
}

此端点工作正常.我明白了

This endpoint works fine. I get

<employees>
  <employee>
    <id>2</id>
    <name>Ana</name>
  </employee>
</employees>

但是,如果我将方法更改为返回 Response 对象,并将员工列表放入响应正文中,如下所示:

However, if I change the method to return a Response object, and put the employee list in the response body, like this:

@GET
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/")
public Response findEmployees(
    @QueryParam("name") String name,
    @QueryParam("page") String pageNumber,
    @QueryParam("pageSize") String pageSize) {
    ...
    List<Employee> employees = employeeService.findEmployees(...);

    return Response.ok().entity(employees).build();
}

由于以下异常,端点导致 HTTP 500:

the endpoint results in an HTTP 500 due to the following exception:

javax.ws.rs.WebApplicationException:com.sun.jersey.api.MessageException:Java 类 java.util.ArrayList、Java 类型类 java.util.ArrayList 和 MIME 媒体的消息体编写器找不到类型 application/xml

在第一种情况下,JAX-RS 显然已安排适当的消息编写器在返回集合时启动.将集合放在实体主体中时不会发生这种情况似乎有些不一致.在返回响应时,我可以采取什么方法来实现列表的自动 JAXB 序列化?

In the first case, JAX-RS has obviously arranged for the proper message writer to kick in when returning a collection. It seems somewhat inconsistent that this doesn't happen when the collection is placed in the entity body. What approach can I take to get the automatic JAXB serialization of the list to happen when returning a response?

我知道我可以

  • 只需从资源方法中返回列表
  • 创建一个单独的EmployeeList

但想知道是否有一种很好的方法来使用 Response 对象并获取列表以序列化 而无需创建我自己的包装类.

but was wondering whether there is a nice way to use the Response object and get the list to serialize without creating my own wrapper class.

推荐答案

您可以将 List 包装在 GenericEntity 的实例中以保留类型信息:

You can wrap the List<Employee> in an instance of GenericEntity to preserve the type information:

这篇关于JAX-RS:返回响应对象时如何自动序列化集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:39