Below is the json response retrieved from the api
[
{"employee":{"id":1,"name":"somu","employee_company":{"id":100,"name":"comp1"}}},
{"employee": {"id":2,"name":"raju","employee_company":{"id":101,"name":"comp2"}}},
{"employee":{"id":3,"name":"nagu","employee_company":{"id":105,"name":"comp5"}}}
]
Not sure how to define the java equivalent structure to consume the above json response
a. List<EmployeeDTO> where EmployeeDTO has Employee object and EmployeeCompany Object (OR)
b. List<Map<String, EmployeeDTO>> where EmployeeDTO has id, name attribute and EmployeeCompany Object
restTemplate.exchange
(RequestEntity.get(new URI(url)).headers(headers).build(), EmployeeDTO.class);
(or)
` restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<EmployeeDTO>>() {}
);`
1. EmployeeDTO -> Employee + EmployeeCompany
2. Employee + EmployeeCompany (no employee DTO)
Can you please help me with the DTO structure align with the above json and also the rest API call with
response class?
Thanks
>Solution :
- For fast convert u can use
https://json2csharp.com/code-converters/json-to-pojo
it offers
// import com.fasterxml.jackson.databind.ObjectMapper; // version 2.11.1
// import com.fasterxml.jackson.annotation.JsonProperty; // version 2.11.1
/* ObjectMapper om = new ObjectMapper();
Root[] root = om.readValue(myJsonString, Root[].class); */
public class Employee{
public int id;
public String name;
public EmployeeCompany employee_company;
}
public class EmployeeCompany{
public int id;
public String name;
}
public class Root{
public Employee employee;
}
- Call remote url and get a list
https://www.baeldung.com/spring-rest-template-list
EmployeeList response = restTemplate.getForObject(
"http://localhost:8080/employees",
EmployeeList.class);
List<Employee> employees = response.getEmployees();