Search code examples
javajsonspringjacksonresttemplate

Rest Template binding with root array


I'm trying to use Rest Template to bind JSON to POJOs.

Imagine having a SpaceX class and a Rocket class, while the SpaceX class has a List<Rocket> attribute. I use the @JsonProperty annotation to let the Rest Template bind "Rocket ID" and "name" inside a Rocket object automatically.

My JSON file starts as array like following:

[
  {
    "Rocket ID": "1",
     "name": "A"
  },
  {
    "Rocket ID": "2",
     "name": "B"
  }
]

I'm able to consume the JSON file and fill a List<Rocket> manually like this:

public <T> List<T> createObjectsFromJSON(Class<T[]> responseType) {
    ResponseEntity<T[]> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, request, responseType);
    T[] objects = responseEntity.getBody();
    List<T> list = Arrays.asList(objects);
    return list;
}

but I want to create a SpaceXobject and let the Rest Template fill in the List<Rocket> automatically. I can't wrap my head around the answer on how to do it. I can't tell the Rest Template to bind the list via @JsonProperty, because there is no name.


Solution

  • If you can't change JSON structure than you have to write custom serialization and deserialization logic. You can use @JsonCreator and @JsonValue annotations:

    The @JsonCreator annotation is used to tune the constructor/factory used in deserialization. It’s very helpful when we need to deserialize some JSON that doesn’t exactly match the target entity we need to get.

    @JsonValue indicates a single method that should be used to serialize the entire instance.

    Or @JsonSerialize and @JsonDeserialize:

    @JsonSerialize is used to indicate a custom serializer will be used to marshall the entity.

    @JsonDeserialize is used to indicate the use of a custom deserializer.

    This article contains more details and examples: http://www.baeldung.com/jackson-annotations