Moshe Tsabari
Moshe Tsabari

Reputation: 372

Jackson Parser To Java Object

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

when I am using like this its working

 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

Upvotes: 1

Views: 89

Answers (1)

Andy Turner
Andy Turner

Reputation: 140534

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

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);
  }
}

Upvotes: 1

Related Questions