【问题标题】:Generic JSON deserialization通用 JSON 反序列化
【发布时间】:2019-11-21 11:21:47
【问题描述】:

我有这门课:

public static class Version {
    @Getter private float version;
    @Getter private String url;
    @Getter private String label;
}

我正在尝试编写一个通用方法,用于从 JSON 中反序列化 this 和其他类的实例。 到目前为止,我有:

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?

【问题讨论】:

标签: generics jackson


【解决方案1】:

使用这个方法。

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

【讨论】:

    猜你喜欢
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    相关资源
    最近更新 更多