Jackson 和泛型类型引用 [英] Jackson and generic type reference

查看:47
本文介绍了Jackson 和泛型类型引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 jackson json 库用于通用方法,如下所示:

I want to use jackson json library for a generic method as follows:

public MyRequest<T> tester() {
    TypeReference<MyWrapper<T>> typeRef = new TypeReference<MyWrapper<T>>();  
    MyWrapper<T> requestWrapper = (MyWrapper<T>) JsonConverter.fromJson(jsonRequest, typeRef);
    return requestWrapper.getRequest();
}

public class MyWrapper<T> {

    private MyRequest<T> request;

    public MyRequest<T> getRequest() {
        return request;
    }

    public void setRequest(MyRequest<T> request) {
        this.request = request;
    }
}

public class MyRequest<T> {
     private List<T> myobjects;
        
     public void setMyObjects(List<T> ets) {
         this.myobjects = ets;
     }

     @NotNull
     @JsonIgnore
     public T getMyObject() {
         return myobjects.get(0);
     }
}

现在的问题是,当我调用请求对象内的 getMyObject() 时,Jackson 将嵌套的自定义对象作为 LinkedHashMap 返回.有什么方法可以指定需要返回 T 对象吗?例如:如果我发送类型为 Customer 的对象,那么应该从该列表返回 Customer?

Now the problem is that when I call getMyObject() which is inside the request object Jackson returns the nested custom object as a LinkedHashMap. Is there any way in which I specify that T object needs to be returned? For example: if I sent object of type Customer then Customer should be returned from that List?

推荐答案

这是 Java 类型擦除的一个众所周知的问题:T 只是一个类型变量,您必须指明实际的类,通常作为 Class 参数.如果没有这些信息,最好的办法就是使用边界;并且普通的 T 与T extends Object"大致相同.然后 Jackson 会将 JSON 对象绑定为 Maps.

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

这种情况下,tester方法需要访问Class,可以构造

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

然后

List<Foo> list = mapper.readValue(new File("input.json"), type);

这篇关于Jackson 和泛型类型引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆