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?

Upvotes: 3

Views: 2637

Answers (2)

Eklavya
Eklavya

Reputation: 18430

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();

Upvotes: 3

Pankaj
Pankaj

Reputation: 2678

Looks like you are trying to map array to object. You can do something like this

ResponseEntity<Test[]> response =
  restTemplate.getForEntity(
  url,
  Test[].class);
Test[] employees = response.getBody();

For more information check this post

Upvotes: 0

Related Questions