javarest

De-serialize array from RestClient response


I'm able to de-serialize response for "get one" endpoint to desired object type:

        import org.springframework.web.client.RestClient;
        ...
        RestClient restClient = RestClient.create();
        return restClient.get()
            .uri(url)
            .header("Authorization", token)
            .retrieve()
            .body(CustomType.class);

However "get all" endpoint returns an array. I'm able to de-serialize response like this:

        import org.springframework.web.client.RestClient;
        ...
        RestClient restClient = RestClient.create();
        return restClient.get()
            .uri(url)
            .header("Authorization", token)
            .retrieve()
            .body(ArrayList.class);

This snippet returns an ArrayList of LinkedHashMaps, but is it possible to return ArrayList or array of CustomType objects?


Solution

  • you can use a ParameterizedTypeReference to properly deserialize the JSON array into your custom objects.

    
        RestClient restClient = RestClient.create();
    return restClient.get()
        .uri(url)
        .header("Authorization", token)
        .retrieve()
        .body(new ParameterizedTypeReference<ArrayList<CustomType>>() {});