Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What should be the json format for this json response?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

  1. 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;
}
  1. 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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading