Kaj
Kaj

Reputation: 2503

Convert multiple json results to iterable

I am trying to map json results to an Iterable of my class instance.

If I get 1 object result I convert it from JSON to a class instance using this methods:

private ObjectReader personReader = null;
private ObjectReader getPersonReader() {

    if (personReader != null) return personReader;

    ObjectMapper mapper = new ObjectMapper();
    return personReader = mapper.reader(Person.class);
}
public Person response2Person(ResponseEntity<String> response) {
    try {
        return getPersonReader().readValue(response.getBody());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

What shoul my getPersonsReader method look like to convert a JSON string, containing multiple results?

public Iterable<Person> response2Persons(ResponseEntity<String> response) {
    try {
        return getPersonsReader().readValue(response.getBody());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

The JSON String looks like this:

[
    {
        "firstname": "Foo",
        "lastname": "Bar"
    },
    {
        "firstname": "Elvis",
        "lastname": "Presley"
    }
]

Upvotes: 2

Views: 633

Answers (1)

araqnid
araqnid

Reputation: 133662

You can use TypeReference to make a compile-time reference to a parameterised type:

mapper.reader(new TypeReference<List<Person>>() {});

Upvotes: 3

Related Questions