Search code examples
javajsonspringspring-mvcresttemplate

Spring Rest Template Json output mapping to Object


When i make the API call using Spring Rest template, getting Json response like below

[
  {
    "Employee Name": "xyz123",       
    "Employee Id": "12345"
  }
]

I was created object to map the json response like below:

public class Test {
    
    @JsonProperty("Employee Name")
    private String employeeName;
    
    @JsonProperty("Employee Id")
    private String employeeId;

}

But I am getting below error when i make rest api call:

JSON parse error: Cannot deserialize instance of com.pojo.Emp out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of com.pojo.Emp out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1

How to map the Rest template Json response to object when Json has spaces in parameter keys?


Solution

  • Your JSON response is an array of object since it's wrapped in [], so map the data into a List<Emp>. Here used ParameterizedTypeReference to create the TypeReference of List<Emp>

    ResponseEntity<List<Emp>> response = restTemplate.exchange(endpointUrl, 
                                                      HttpMethod.GET,httpEntity,
                                                 new ParameterizedTypeReference<List<Emp>>(){}); 
    List<Emp> employees = response.getBody();