java - JAXRS/RestEasy 中的@Produces 集合

标签 java jax-rs resteasy wildfly-9

我发现了一些我无法理解的奇怪行为。

我测试了4个类似的例子:

1

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response produce() {
    List<Book> books = Arrays
            .asList(new Book[] { 
                    new Book("aaa", "AAA", "12345"), 
                    new Book("bbb", "BBB", "09876") 
                    });
    return Response.ok(books).build();
}

2

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Book> produce() {
    List<Book> books = Arrays
            .asList(new Book[] { 
                    new Book("aaa", "AAA", "12345"), 
                    new Book("bbb", "BBB", "09876") 
                    });
    return books;
}

3

@GET
@Produces(MediaType.APPLICATION_XML)
public List<Book> produce() {
    List<Book> books = Arrays
            .asList(new Book[] { 
                    new Book("aaa", "AAA", "12345"), 
                    new Book("bbb", "BBB", "09876") 
                    });
    return books;
}

4

@GET
@Produces(MediaType.APPLICATION_XML)
public Response produce() {
    List<Book> books = Arrays
            .asList(new Book[] { 
                    new Book("aaa", "AAA", "12345"), 
                    new Book("bbb", "BBB", "09876") 
                    });
    return Response.ok(books).build();
}

在#1、#2、#3 中一切正常,但第 4 个示例抛出:

Could not find MessageBodyWriter for response object of type: java.util.Arrays$ArrayList of media type: application/xml.

我在 Wildfly 9 上运行它,我想知道它是否与 RestEasy 或 JaxRS 一般相关?我知道我可以通过在 GenericEntity 中包装集合来修复它,但我不理解这种不一致的行为。

最佳答案

问题是缺少类型信息。这是处理 XML 序列化的 JAXB 所必需的。

1 和 2 之所以有效,是因为 Jackson 被用于 JSON,它通常不需要知道类型信息,因为它只是内省(introspection)属性。

3 之所以有效,是因为类型信息是通过方法返回类型获知的。

4 不起作用,因为没有类型信息。它被 type erasure 删除了.那就是GenericEntity来救援。它存储类型信息。

GenericEntity

Normally type erasure removes generic type information such that a Response instance that contains, e.g., an entity of type List<String> appears to contain a raw List<?> at runtime. When the generic type is required to select a suitable MessageBodyWriter, this class may be used to wrap the entity and capture its generic type.

关于java - JAXRS/RestEasy 中的@Produces 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35039294/

相关文章:

java - 有没有办法在我的 android 项目中模拟 JNI 方法来进行 Junit 测试?

java - Amazon S3 上传挂起 100%

java - 为什么 UriInfo.getQueryParameters() 不解码 '+' ?

quarkus - Quarkus Resteasy 响应式(Reactive)中 Uni<List<T>> 与 Multi<T> 之间有区别吗?

javax.ws.rs.NotFoundException : RESTEASY003210: Could not find resource for full path: using RestEASY, Intellij IDEA 16.1,Tomcat 8.0.33

java - 如何在不使用 addSnapshotListener 的情况下检索文档大小?

java - Bean 验证仅适用于 Spring 中的 Controller 方法?

java - 如何将 javax.ws.rs.core.Feature 与 CXF 一起使用?

java - 如何在两种情况下都具有根元素的 Jersey 中获取 JSON 和 XML 响应?

java - 使用 @RolesAllowed 通过 RESTEasy 和 Jackson 过滤实体属性