使用Jackson在反序列化期间对列表属性中的对象列表进行分组

时间:2014-01-20 15:17:01

标签: java json list jackson json-deserialization

我的JSON结构如下所示:

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

和相应的Java Object for Data binding:

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

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

现在出现了棘手的部分:我想要做的是将JSON反序列化为类似下面的代码片段,仅对此类进行更改

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

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

非常感谢McFarlane

1 个答案:

答案 0 :(得分:0)

TypeReferenceas described in this link的重点是使用泛型类型参数来检索类型信息。

在内部,它执行以下操作

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

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

正确的用法是

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

换句话说,不,您需要更改映射器代码才能达到您想要的效果。

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