当使用ObjectMapper将json字符串转换为实体时,我可以将其通用化为:
public E getConvertedAs(String body, Class type) throws IOException {
return mapper.readValue(body, type);
}
现在,假设我想阅读收藏集.我可以:
List someEntityList = asList(mapper.readValue(body, SomeEntity[].class));
List someOtherEntityList = asList(mapper.readValue(body, SomeOtherEntity[].class));
我想写一个上述的等效方法,但要用于集合.由于您无法在Java中使用通用数组,因此无法执行以下操作:
public List getConvertedListAs(String body, Class type) {
return mapper.readValue(body, type[].class);
}
Here有一个几乎可以解决的解决方案:
mapper.readValue(jsonString, new TypeReference>() {});
问题在于它不会反序列化为E列表,而是反序列化为LinkedHashMap.Entry.是否有进一步的方法,如下所示?
public List getConvertedListAs(String body, Class type) {
mapper.readValue(body, new TypeReference>() {}); // Doesn't compile
}