【问题标题】:RestRessource not working anymore after changing Return Type from List to Response将返回类型从列表更改为响应后,RestRessource 不再工作
【发布时间】:2015-08-21 08:15:54
【问题描述】:

我有一个带有 RestRessource 类别的简单 Rest 示例(取自 Jersey Maven Archetype)

@Path("category")
@Produces(MediaType.APPLICATION_JSON)
public class CategoryRessource {

    CategoryService service = new CategoryService();

    @GET
    public List<Category> getCategories() throws SQLException{      
        List<Category> categories = (ArrayList<Category>) service.getAllCategories();
        return categories;
    }

有了这个一切正常。
但现在我想将响应类型更改为如下所示的响应,但如果我访问它,则会出现此错误:

09:30:04,688 SEVERE [org.glassfish.jersey.message.internal.WriterInterceptorExecutor] (default task-1) MessageBodyWriter
 not found for media type=text/html, type=class java.util.ArrayList, genericType=class java.util.ArrayList.

具有返回类型响应的资源类:

@Path("category")
@Produces(MediaType.APPLICATION_JSON)
public class CategoryRessource {

    CategoryService service = new CategoryService();

    @GET
    public Response getCategories() throws SQLException{        
        List<Category> categories = (ArrayList<Category>) service.getAllCategories();
        return Response .status(Status.OK)
                        .entity(categories)
                        .type(MediaType.APPLICATION_JSON)
                        .build();
    }

这也是我的类别模型类

@XmlRootElement
public class Category {
    private String name;

    public Category(){  
    }

    public String getName() {
        return id;
    }
    public void setName(String name) {
        this.name = name;
    }

【问题讨论】:

    标签: java rest jersey response


    【解决方案1】:

    这是一个与 MOXy 相关的问题(它使用了 JAXB)。序列化需要类型信息。在签名中返回实际的泛型类型时,类型是已知的。但是在使用Response 时,它是未知的。

    在 JAX-RS 中处理这种情况的一般方法是将泛型类型包装在 GenericEntity 中。例如

    ArrayList<Category> cats = new ArrayList<>();
    cats.add(new Category("Cat 1"));
    cats.add(new Category("Cat 2"));
    
    GenericEntity<List<Category>> entity = new GenericEntity<List<Category>>(cats){};
    return Response.ok(entity).build();
    

    另一种选择是不使用 MOXy,而只使用 Jackson。有了杰克逊,我们就不会遇到这个问题。它知道如何通过简单地自省属性来进行序列化。只需将 MOXy 换成

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey2.version}</version>  <!-- not needed if you have 
                                                    bom from archetype -->
    </dependency>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      相关资源
      最近更新 更多