2

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?

12
  • what are you using for JSON mapping? Jackson or Gson? I don't see it in the code. Commented Feb 28, 2017 at 20:47
  • Apologies. It's via Jackson. Spring boot uses Jackson JSON library. Commented Feb 28, 2017 at 20:48
  • Thanks for the edit. I don't see any annotations in your class file Commented Feb 28, 2017 at 20:48
  • 2
    Perhaps you should initialize your map to an empty instance of a Map implementation like new HashMap(); Commented Feb 28, 2017 at 20:51
  • I'm very unfamiliar with Jackson. What annotations should I be using? I got one example working before with no bindings (as per this tutorial: spring.io/guides/gs/consuming-rest) Commented Feb 28, 2017 at 20:51

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I'll give this a try and let you know.
Happy to help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.