杰克逊反序列化具有未知属性名称的泛型 [英] Jackson deserialize generic with unknown property name
问题描述
我有以下JSON
.我正在使用 Jackson
解析器
I have following JSON
. And I am parsing it using Jackson
Parser
{
"code": 0,
"response": {
"pagination": {
"page": 1,
"limit": 20,
"count": 5,
"pageCount": 1
},
"random": [
....
]
}
}
现在,我已经为各种random
对象创建了简单的 POJO
类.我期望3-4种不同类型的 random
对象.因此,我没有为不同类型的随机"对象创建不同的包装器类,而是创建了一个通用的包装器类.
Now I have simple POJO
classes created for various random
object. I expect 3-4 different types of random
object. So instead of creating different wrapper classes for different types of 'random' object I created a generic one
编辑类:
public class PaginatedResponse<E> {
private Pagination pagination;
private List<E> responseList;
public Pagination getPagination() {
return pagination;
}
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
public List<E> getResponseList() {
return responseList;
}
public void setResponseList(List<E> responseList) {
this.responseList = responseList;
}
}
现在我用于映射它,
JsonNode tree = mapper.readTree(response);
TypeReference<PaginatedResponse<LocationParent>> ref = new TypeReference<PaginatedResponse<LocationParent>>() { };
PaginatedResponse<LocationParent> resp = mapper.convertValue(tree.get("response"), ref);
但是我无法映射responseList
.我得到了 pagination
对象,但responseList
始终为null.现在如何为responseList
动态提供property name
.
But i am not able to map responseList
. I get the pagination
object but the responseList
is always null. Now how to dynamically provide property name
for responseList
.
请帮助
推荐答案
变量值类型需要的是多态类型的处理.仅泛型类型无济于事,因为反序列化方面不知道要使用哪种类型.
What you need for variable value type is handling for polymorphic types. Generic types alone won't help, since deserialization side would not know what type to use.
您可以使用注释@JsonTypeInfo
启用多态类型处理;但是在这种特殊情况下的问题是,您想要一个任意类型的事物的List
-由于类型擦除,所有Java列表实际上只是List<Object>
;没有元素的输入.
You can enable polymorphic type handling with annotation @JsonTypeInfo
; but a problem in this particular case is that you want a List
of things of arbitrary type -- due to type-erasure, all Java Lists are really just List<Object>
; there is no typing for elements.
如果是我,我可能会子类化PaginatedResponse
,然后在基类中添加@JsonTypeInfo
,例如:
If it was me, I would probably sub-class PaginatedResponse
and just add @JsonTypeInfo
in base class, like:
@JsonTypeInfo(...) // see javadocs for properties needed
public abstract class PaginatedResponse<T> {
public Pagination pagination;
// .. and so on
}
public class PaginatedFooResponse<Foo> { }
在这里使用子类的原因仅仅是为了使反序列化器能够找出给定响应对象类型的元素类型.响应对象将具有类型(PaginatedFooResposne
),并且可以使用该类型的元素.
The reason to use sub-classing here is simply make it possible for deserializer to figure out element type, given type of response object. Response object will have type (PaginatedFooResposne
), and from that type of elements is available.
这篇关于杰克逊反序列化具有未知属性名称的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!