Search code examples
javaspringresttemplate

How get JSON array with resttemplate


API response

{
    "status": "success",
    "data": [
        {
            "id": "1",
            "employee_name": "Tiger Nixon",
            "employee_salary": "320800",
            "employee_age": "61",
            "profile_image": ""
        },
...
]
}

public class Data {

private int id;

private String employeeName;

private int employeeSalary;

private int employeeAge;

private String profileImage;

}

Setter getter and constructor has omitted

public class Employees {

private String status;
private Data[] datas;

}

public Employees getProductList() {
    ResponseEntity<Employees> result = restTemplate.exchange("http://dummy.restapiexample.com/api/v1/employees",
            HttpMethod.GET, null, Employees.class);
    return result.getBody();
}

And this is returned

Employees{status=success, datas=null}

Why datas is null?

Thanks for any help :)


Solution

  • Please annotate your fields as @JsonProperty and fields names to match input json:

    public class Data {
        @JsonProperty
        private String id;
        @JsonProperty
        private String employee_name;
        @JsonProperty
        private String employee_salary;
        @JsonProperty
        private String employee_age;
        @JsonProperty
        private String profile_image;
    }
    
    public class Employees {
        @JsonProperty
        private String status;
        @JsonProperty
        private List<Data> data;
    }