Search code examples
javaresteasyquarkusjackson2

Parse JSON array from a response body using Resteasy and Jackson annotations


I'm using Resteasy with Quarkus, and Jackson annotations (io.quarkus.quarkus-resteasy, io.quarkus.quarkus-resteasy-jackson, version 1.13.2.Final).

I need to parse this kind of response from an API I call :

[
  {
    "name": "John Smith",
    "age": 43
  },
  {
    "name": "Jane Doe",
    "age": 27
  }
]

I can't change this response (wrap this array inside an object with a property, for example). The root element of the response body is an array.

Here is the model class:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {

    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name,
                  @JsonProperty("age") int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

And here is how I request the API:

ResteasyClient resteasyClient = new ResteasyClientBuilderImpl().build();
try {
    Response response = resteasyClient.target("/api/path")
            .queryParam("param1", "value1")
            .request()
            .get();

    List<Perso> person = response.readEntity( /* ? */ );
}
catch (ProcessingException e) {
    // Handle the error...
}

I can't use List<Person>.class in the readEntity method ("Cannot select from parameterized type").

I tried creating a Persons wrapper object which contains the list. But the JSON content in not an object with a list property, it is an array. So it doesn't work.


Solution

  • The readEntity method has a variant that, instead of a Class, takes a GenericType. You can use readEntity(new GenericType<List<Person>>() {}).

    In case you're interested, the GenericType class uses a clever trick that, to the best of my knowledge, was first described by Neal Gafter in his Super Type Tokens article: http://gafter.blogspot.com/2006/12/super-type-tokens.html