【问题标题】:spring restTemplate dynamic mappingspring restTemplate 动态映射
【发布时间】:2018-04-26 00:40:50
【问题描述】:

我正在使用 spring restTemplate 将响应映射到 POJO。 rest api 的响应是这样的:

"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"

处理这种情况的推荐方法是什么?

【问题讨论】:

    标签: java json spring-boot jackson resttemplate


    【解决方案1】:

    我会推荐 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 告诉 Jackson 这是一个基类,类型将由名为 "type" 的 JSON 字段确定

    JsonSubTypesAttribute 的子类型映射到 JSON 中 "type" 的值。

    如果您为 Assignments 添加适当的子类型,并且 getters/setters Jackson 将能够解析您的 JSON。

    【讨论】:

      猜你喜欢
      • 2014-11-13
      • 1970-01-01
      • 2010-10-28
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多