我有一个如下所示的 JSON 结构:
[
{
"id": 0,
"name": "Foo"
},
{
"id": 1,
"name": "Bar"
}
]
以及相应的用于数据绑定(bind)的 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;
}
是否有任何注释可以帮助我实现我想要的目标,或者我是否必须对映射器代码进行更改?
提前非常感谢,麦克法兰
最佳答案
TypeReference
的全部要点, as 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 .
关于java - 使用 Jackson 反序列化期间对列表属性中的对象列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237572/