例如,我有一个包装器json对象。
{
"id": 23,
"name": "teset",
"type": "person",
"_data": {
"address": 23432
}
}我的java对象应该如下所示
public class Wrapper<D>{
private Integer id;
private String type;
@JsonProperty("_data")
private D data;
...
}我找不到让对象映射器这样做的方法
Wrapper<Person> wrapped = objectMapper.readValue(jsonStream,Wrapper.class);
如果不支持这一点,我就无法在杰克逊中找到很多关于仿制药的信息。
发布于 2016-10-14 15:18:38
您的代码有几个问题:
Wrapper调用中指定所需的参数化readValue类型。您可以使用(简化的表单):Wrapper<Person> wrapped = om.readValue(json, new TypeReference<Wrapper<Person>>() {});来修复这个问题。name属性,它显然不存在于Wrapper类中。您可以将其配置为忽略未知属性:ObjectMapper:objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);下面是一个例子:
public static class Wrapper<D> {
// making fields public for simplicity,
// use public getters and private fields of course
public Integer id;
public String type;
@JsonProperty("_data")
public D data;
}
public static class Person {
// adding address field as a public int,
// same as above, encapsulate properly in real life
public int address;
}然后,在一个主要的方法某处..。
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// your example JSON
String json = "{\"id\":23,\"name\":\"test\",\"type\":\"person\",\"_data\":"
+ "{\"address\":23432}}";
Wrapper<Person> wrapped = om.readValue(
json, new TypeReference<Wrapper<Person>>() {}
);
// printing class/hashCode of the resolved generic type
System.out.println(wrapped.data);
// casting as Person and printing actual property
System.out.println(((Person)wrapped.data).address);输出(类似于.)
test.Main$Person@dfd3711
23432 for TypeReference,来自文档
此泛型抽象类用于通过子类获取完整的泛型类型信息;必须将其转换为ResolvedType实现(由JavaType从"databind“包实现)。类基于http://gafter.blogspot.com/2006/12/super-type-tokens.html的思想,其他的想法(来自本文注释中的建议)是要求类似的伪实现(只要它强制实现具有泛型类型的方法就行了)。以确保确实给出了Type参数。 使用是通过子类进行的:下面是实例化泛型类型列表引用的一种方法:
TypeReference ref = new TypeReference<List<Integer>>() { };可以传递给接受TypeReference的方法,也可以使用TypeFactory进行解析以获得ResolvedType。
https://stackoverflow.com/questions/40046474
复制相似问题