杰克逊解析器到Java对象 [英] Jackson Parser To Java Object

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

问题描述

我正在使用Jackson解析对象.有时我需要对象列表.

I am using Jackson to parse object. sometime I need list of objects.

当我这样使用时

 List<MyObject> mapper.readValue(file , new TypeReference<MyObject>() {})

但是当我这样使用它时,它就不起作用了

but when I am using it like this its not working

public class JsonMocksRepository<T>{

    public  T getObject() throws Exception{

        return mapper.readValue(file ,new TypeReference<T>());
    }
}

我需要做什么? 基本上,我想使用泛型来获取正确的类

What I need to do ? Basically I want to use generics to get the right class

推荐答案

这是因为类型擦除.在运行时没有可用的T表示的实际类型的信息,因此您的TypeReference实际上就是TypeReference<Object>.

This is because of type erasure. There is no information about the actual type represented by T available at runtime, so your TypeReference will be effectively be simply TypeReference<Object>.

如果要使用JsonMocksRepository的通用实例,则需要在构造时注入TypeReference:

If you want a generic instance of JsonMocksRepository, you will need to inject the TypeReference at construction time:

public class JsonMocksRepository<T>{
  private final TypeReference<T> typeRef;

  public JsonMocksRepository(TypeReference<T> typeRef) {
    this.typeRef = typeRef;
  }

  public T getObject() throws Exception{
    return mapper.readValue(file, typeRef);
  }
}

这篇关于杰克逊解析器到Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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