Search code examples
javajsonspringjacksonresttemplate

Reading JSON map structure via spring boot


If I have the following JSON structure returned by my REST service:

{
   "foo" : {
      "id" : "baz"
   }
   "qux" : {
      "id" : "toto"
   }
}

To me it looks like a map structure. I am not sure how I can read this using spring boot (via Jackson).

I have defined my JSON bind class like so:

public class Foos {

   private Map<String, Foo> fooInstances;

   private void setFooInstances(Map<String, Foo> fooInstances) {
      this.fooInstances = fooInstances;
   }

   private Map<String, Foo> getFooInstances() {
      return fooInstances;
   }

}

And a Foo instance looks like so:

public class Foo {

   private String id;


   private void setId(String id) {
      this.id = id;
   }

   private String getId() {
      return id;
   }

}

The spring code for making the request is like so:

RestTemplate template = new RestTemplate();
ResponseEntity<Foos> responseEntity = (ResponseEntity<Foos>) template.getForEntity(serviceEndpointURL, Foos.class);

I originally had a START_OBJECT error which I fixed by creating the Foos class with the corresponding map and now I don't get an error. Instead I get a populated ResponseEntity, with a 'Foos' instance, but the map is null. Any idea what I am doing wrong?


Solution

  • Modify your Foos class like this

    public class Foos {
    
    @JsonIgnore
    private Map<String, Object> properties = new HashMap<String, Object>();
    
    @JsonAnyGetter
    public Map<String, Object> getProperties() {
    return this.properties;
    }
    
    @JsonAnySetter
    public void setProperty(String name, Object value) {
    this.properties.put(name, value);
    }
    }
    

    You can typecast from Object to Foo from the map.

    Let me know if you have any questions!!