When using an ObjectMapper
to transform a json String
into an entity, I can make it generic as:
public <E> E getConvertedAs(String body, Class<E> type) throws IOException {
return mapper.readValue(body, type);
}
Now let's say I want to read collections. I can do:
List<SomeEntity> someEntityList = asList(mapper.readValue(body, SomeEntity[].class));
List<SomeOtherEntity> someOtherEntityList = asList(mapper.readValue(body, SomeOtherEntity[].class));
I would like to write an equivalent method of the above, but for collections. Since you can't have generic arrays in java, something like this won't work:
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
return mapper.readValue(body, type[].class);
}
Here there is a solution that almost works:
mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});
The problem is that it doesn't deserialize into a list of E
, but of LinkedHashMap.Entry
. Is there any way of going going a step further, something like the following?
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
mapper.readValue(body, new TypeReference<List<type>>() {}); // Doesn't compile
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…