adesai
adesai

Reputation: 420

Map JSON properties to a Java Map in Spring RestTemplate response

I have following JSON response coming from a Rest call:

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

I am using Spring RestTemplate to make the rest call and I would like to map the response to a Java Object as below:

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

    private Map<String, String> allTheRestProps;
}

Is it possible to do this with Jackson annotations without using String as a response and map it manually?

Upvotes: 1

Views: 652

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38645

Use JsonAnySetter annotation:

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);
    }
}

Upvotes: 1

Related Questions