Search code examples
jsonrestspring-bootresttemplate

How to map getBody array list response of RestTemplate into class in Spring boot?


I've used restTemplate to get the details from a third party API.

Where, below code give me a response in string (using response.getBody())

ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

Example of JSON

{"Entries":[{"EntryId":"1","Field1":"1","Field2":"2"},{"EntryId":"2","Field1":"3","Field2":"4"}]}

I've also created a class called Entries,

@JsonIgnoreProperties(ignoreUnknown=true)
public class Entries {

    @JsonProperty("EntryId")
    private String entryId;

    @JsonProperty("Field1")
    private String field1;

    @JsonProperty("Field2")
    private String field2;

//getter and setters

Is there any way to map JSON Array with Entires class using RestTemplate?


Solution

  • There are two ways,

    [1] Using ObjectMapper

    ObjectMapper mapper = new ObjectMapper();
            Entries obj = mapper.readValue(rrateResponse.getBody(), Entries.class);
    

    [2] Passing an Entries class

    ResponseEntity<Entries> result = restTemplate.exchange(uri, HttpMethod.GET, entity, Entries.class);
    

    The only missing thing was an Entries which is mentioned below.

    @JsonIgnoreProperties(ignoreUnknown=true)
    public class Entries {
    
        @JsonProperty("Entries")
        private List<Entry> Entries;
    
    //getter and setter