【问题标题】:Group list of objects in a list attribute during deserialization using Jackson使用 Jackson 反序列化期间列表属性中的对象组列表
【发布时间】:2014-01-20 15:17:00
【问题描述】:

我有一个如下所示的 JSON 结构:

[
    {
        "id": 0,
        "name": "Foo"
    },
    {
        "id": 1,
        "name": "Bar"
    }
]

以及对应的用于数据绑定的 Java 对象:

public class Thing {
    public int id;
    public String name;
}

我知道如何将 JSON 列表反序列化为 Thing 列表。

现在棘手的部分来了:我要做的是将 JSON 反序列化为一个类似于以下 sn-p 的类只对此类进行更改

public class Things {
    private List<Thing> things;

    public void setThings(List<Thing> things) {
        this.things = things;
    }

    public List<Thing> getThings() {
        return this.things;
    }
}

这是因为 JSON 反序列化是通过使用像这样的 ObjectMapper 在我们的应用程序中构建的:

private static <T> T parseJson(Object source, Class<T> t) {

    TypeReference<T> ref = new TypeReference<T>() {
    };
    TypeFactory tf = TypeFactory.defaultInstance();

    //[...]

    obj = mapper.readValue((String) source, tf.constructType(ref));

    //[...]

    return obj;
}

是否有任何注释可以实现我想要的,或者我必须对映射器代码进行更改?

非常感谢,麦克法兰

【问题讨论】:

    标签: java json list jackson json-deserialization


    【解决方案1】:

    TypeReferenceas described in this link 的全部意义在于使用泛型类型参数来检索类型信息。

    在内部它执行以下操作

    Type superClass = getClass().getGenericSuperclass();
    ...
    _type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
    

    getActualTypeArguments()[0] 将为您提供实际的类型参数。在这种情况下,这将是类型变量 T,无论您为方法的 Class&lt;T&gt; t 参数传递什么。

    正确的用法是

    TypeReference<List<Thing>> ref = new TypeReference<List<Thing>>() {};
    ...
    List<Thing> thingsList = ...;
    Things things = new Things();
    things.setThings(thingsList);
    

    换句话说,不,您需要更改映射器代码以实现您想要的。

    据我所知,您无法将根 JSON 数组映射为类的属性。替代方案是上面的TypeReference 示例或here 中的其他一些示例。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2019-10-25
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      相关资源
      最近更新 更多