我有这门课:
public static class Version {
@Getter private float version;
@Getter private String url;
@Getter private String label;
}
我正在尝试编写一个通用方法,用于从 JSON 反序列化此类和其他类的实例。到目前为止,我有:
private <T> List<T> deserializeJSONList(String json) {
try {
TypeReference reference = new TypeReference<List<T>>() {};
return (List<T>) objectMapper.readValue(json, reference);
} catch (JsonProcessingException e) {
throw new RequestException(e);
}
}
我称之为:
List<Version> versions = deserializeJSONList(response.body());
问题是返回的 List 根本不包含 Version 实例,而是包含 LinkedHashMap 的实例,包含表示字段的键/值对。
如何获取泛型方法以返回包含正确类型对象的 List?
使用这种方法。
public static <T> List<T> fromJsonToList(String json, Class<T> clazz) throws IOException {
CollectionType customClassCollection = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
return objectMapper.readValue(json, customClassCollection);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句