【问题标题】:Map JSON properties to a Java Map in Spring RestTemplate response在 Spring RestTemplate 响应中将 JSON 属性映射到 Java Map
【发布时间】:2019-10-08 15:07:58
【问题描述】:

我收到了来自 Rest 调用的以下 JSON 响应:

{
  "config" : {
       "hour" : 1
       "minute" : 60
       "pw" : "password"
   },
  "id" : 12345,
  "enabled" : true,
  "name" : "my-name"
}

我正在使用 Spring RestTemplate 进行其余调用,我想将响应映射到 Java 对象,如下所示:

public Class MyResponse {
    private Map<String, String> config;

    private Map<String, String> allTheRestProps;
}

是否可以在不使用 String 作为响应的情况下使用 Jackson 注释来执行此操作并手动映射它?

【问题讨论】:

  • 所以你想把id,启用,名字放在allTheRestProps

标签: json spring-boot jackson


【解决方案1】:

使用JsonAnySetter注解:

class MyResponse {

    private Map<String, String> config;
    private Map<String, String> allTheRestProps = new HashMap<>();

    public Map<String, String> getConfig() {
        return config;
    }

    public void setConfig(Map<String, String> config) {
        this.config = config;
    }

    public Map<String, String> getAllTheRestProps() {
        return allTheRestProps;
    }

    @JsonAnySetter
    public void setAllTheRestProps(String key, String value) {
        this.allTheRestProps.put(key, value);
    }
}

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 2019-07-22
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2020-07-23
    • 2015-05-07
    相关资源
    最近更新 更多