【问题标题】:How to (completely) deserialize json into a generic List?如何(完全)将 json 反序列化为通用列表?
【发布时间】: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&lt;List&lt;E&gt;&gt;() {} ?
  • @JeremyGrand E 是我的EntryType,这就是给我LinkedHashMap.Entry 列表的原因

标签: java generics jackson json-deserialization


【解决方案1】:

此方法可以帮助将json 读取到一个对象或集合中:

public class JsonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static <T>T toObject(String json, TypeReference<T> typeRef){
        T t = null;
        try {
            t = mapper.readValue(json, typeRef);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
}

读取json列表:

List<Device> devices= JsonUtil.toObject(jsonString,
                            new TypeReference<List<Device>>() {});

读取json到对象:

Device device= JsonUtil.toObject(jsonString,
                                new TypeReference<Device>() {});

【讨论】:

  • 什么是 ObjectMapper?那是在导入库中吗?我得到了各种各样的错误。
【解决方案2】:
public static <E> List<E> fromJson(String in_string, Class<E> in_type) throws JsonParseException, JsonMappingException, IOException{
    return new ObjectMapper().readValue(in_string, new TypeReference<List<E>>() {});
}

在我的电脑上编译。 不过请注意,我还没有对其进行测试。

【讨论】:

  • 请看我对您评论的回复。它编译,但返回LinkedHashMap.Entry 的列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多