我使用spring restTemplate将响应映射到POJO。rest的响应如下:
"attributes": {
"name": {
"type": "String",
"value": ["John Doe"]
},
"permanentResidence": {
"type": "Boolean",
"value": [true]
},
"assignments": {
"type": "Grid",
"value": [{
"id": "AIS002",
"startDate": "12012016",
"endDate": "23112016"
},{
"id": "AIS097",
"startDate": "12042017",
"endDate": "23092017"
}]
}
} 在家长班,我有:
public class Users {
private Map<String, Attribute> attributes;
} 如果所有的值都是字符串类型,那么我可以这样做:
public class Attribute {
private String type;
private String[] value;
} 但是这些值是不同类型的。所以我想做以下几件事:
public class Attribute {
private String type;
private Object[] value;
} 上面的内容应该是可行的,但是在每一步,我都要找出对象的类型。
所以,我的问题是,我能不能得到这样的东西:
public class Attribute {
@JsonProperty("type")
private String type;
@JsonProperty("value")
private String[] stringValues;
@JsonProperty("value")
private Boolean[] booleanValues;
@JsonProperty("value")
private Assignments[] assignmentValues; // for Grid type
}但是它不是工作和抛出错误:Conflicting setter definitions for property "value"
建议如何处理此场景?
发布于 2017-11-14 12:13:21
我建议Jackson在这里使用处理多态性的工具:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = BooleanAttribute.class, name = "Boolean"),
@JsonSubTypes.Type(value = StringAttribute.class, name = "String")
})
class Attribute {
private String type;
}
class BooleanAttribute extends Attribute {
private Boolean[] value;
}
class StringAttribute extends Attribute {
private String[] value;
}JsonTypeInfo告诉杰克逊,这是一个基类,类型将由名为"type"的JSON字段确定
JsonSubTypes将Attribute的子类型映射到JSON中的"type"值。
如果为Assignments和getters/setters添加适当的子类型,Jackson将能够解析您的JSON。
https://stackoverflow.com/questions/47262518
复制相似问题