【问题标题】:Jackson 2.* and json to ArrayList<>Jackson 2.* 和 json 到 ArrayList<>
【发布时间】:2013-11-09 01:46:34
【问题描述】:

我正在尝试将 Json 数组反序列化为对象的 ArrayList。我找到了一些关于我正在尝试做的事情的文档,但是我在编译时遇到了错误。

这是我尝试使用 Jackson 2.2.2 的方法:

ArrayList<Friends> list =  objectMapper.readValue(result, new TypeReference<ArrayList<Friends>>() {});

我得到的错误是:

The method readValue(String, Class<T>) in the type ObjectMapper is not applicable for the arguments (String, new TypeReference<ArrayList<Friends>>(){})

我猜我一直在阅读的一些参考资料是基于 Jackson 的旧版本。如何在 Jackson 2.2 + 中实现这一点

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    尝试以下方法:

    JavaType type = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Friends.class);
    ArrayList<Friends> friendsList = objectMapper.readValue(result, type);
    

    请注意,我是从以下答案中提取的:Jackson and generic type reference

    从 Jackson 1.3(不久前)开始,他们建议您使用 TypeFactory

    编辑
    经过进一步检查,您上面的内容对我有用...我能够将 TypeReference 子类传递给 readValue 并且一切正常。您确定您导入了正确类型的TypeReference 吗?通常这些类型的错误是由于意外导入了错误的类型(其他一些库可能有 TypeReference 类)。

    【讨论】:

    • 太棒了。正是需要什么,我只是无法正确获取构造集合类型。谢谢北极星!
    猜你喜欢
    • 1970-01-01
    • 2013-10-29
    • 2015-02-13
    • 2012-04-07
    • 2013-07-02
    • 2017-08-26
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多