【发布时间】:2017-08-14 07:19:54
【问题描述】:
当使用 ObjectMapper 将 json String 转换为实体时,我可以将其泛型为:
public <E> E getConvertedAs(String body, Class<E> type) throws IOException {
return mapper.readValue(body, type);
}
现在假设我想阅读收藏。我能做到:
List<SomeEntity> someEntityList = asList(mapper.readValue(body, SomeEntity[].class));
List<SomeOtherEntity> someOtherEntityList = asList(mapper.readValue(body, SomeOtherEntity[].class));
我想写一个上述的等效方法,但用于集合。由于您不能在 java 中使用泛型数组,因此这样的事情不会起作用:
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
return mapper.readValue(body, type[].class);
}
Here 有一个几乎可行的解决方案:
mapper.readValue(jsonString, new TypeReference<List<EntryType>>() {});
问题在于它没有反序列化为E 的列表,而是LinkedHashMap.Entry 的列表。有没有办法更进一步,如下所示?
public <E> List<E> getConvertedListAs(String body, Class<E> type) {
mapper.readValue(body, new TypeReference<List<type>>() {}); // Doesn't compile
}
【问题讨论】:
-
也许
new TypeReference<List<E>>() {}? -
@JeremyGrand
E是我的EntryType,这就是给我LinkedHashMap.Entry列表的原因
标签: java generics jackson json-deserialization