1

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

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

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

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

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

非常感谢,麦克法兰

4

1 回答 1

0

如此链接中所述,TypeReference的全部要点是使用泛型类型参数来检索类型信息。

在内部它执行以下操作

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

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

正确的用法是

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

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

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

于 2014-01-20T16:02:00.157 回答