杰克逊和泛型类型参考 [英] Jackson and generic type reference

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

问题描述


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

$ / code>




  public class MyWrapper< T> {

私人MyRequest< T>请求;

public MyRequest< T> getRequest(){
返回请求;
}

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


公共类MyRequest {
私人列表< T> myobjects;

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


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




$ b现在问题是当我调用getMyObject()时,它位于请求对象jackson内部,将嵌套的自定义对象作为LinkedHashMap返回。有什么方法可以指定T对象需要返回吗?例如:如果我发送了Customer类型的对象,那么客户应该从该List中返回。



谢谢。



在这种情况下,测试者方法需要访问Class,并且可以构造

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

然后

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


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{
     private List<T> myobjects;

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

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

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?.

Thanks.

解决方案

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.

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

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

and then

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

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

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