Java recursively populate a Object

388 Views Asked by At

I have a json which is a list of objects with a property of its own type (property manager is of type employee) as below.

  {
  "employee": [
    {
      "id": "",
      "name": "",
      "address": {
        "city": "",
        "state": ""
      },
      "manager": {
        "id": "",
        "name": "",
        "address": {
          "city": "",
          "state": ""
        },
        "manager": null
      }
    }
  ]
}

I have DTO classes with below properties where Employee has a member variable of type Employee.

class Employee{
    private String id;
    priavte Address address;
    private Employee manager
    //getter & setter
}
class Address{
    private String city;
    //getter & setter
}

My requirement is to populate Employee Object recursively (nesting can be of n level Employee -> Manager -> Manager -> Manager ...) and form a new List of Employee Object.

Which will give us the result as below

{
  "employee": [
    {
      "id": ""
      "address": {
        "city": ""
      },
      "manager": {
        "id": ""
        "address": {
          "city": ""
        },
        "manager": null
      }
    }
  ]
}

Any suggestion would be a great help.

1

There are 1 best solutions below

0
Manoj Kumar On BEST ANSWER

Got the way to achieve the solution of above problem

private List<Employee> mapEmployeeModel(List<Employee> employeeList, List<Employee> newEmployeeList) {

        for (Employee emp : employeeList) {
            Employee newEmp = mapEmployee(emp);
            newEmployeeList.add(newEmp);
        }
        
        return newEmployeeList;
}
    
private Employee mapEmployee(Employee emp) {
        
        Employee newEmp = new Employee ();
        newEmp.setId(emp.getId());
        newEmp.setName(emp.getName());
        newEmp.setAddress(mapAddress(emp));
        if(emp.getManager() == null) {
            return newEmp;          
        } else {
            newEmp.setManager(mapEmployee(emp.getManager()));// Recursively setting up the managers
        }
        
        return newEmp;
        
}
    

private Address mapAddress(Employee emp) {
        
        Address address = new Address();
        address.setCity(emp.getAddress().getCity);      
        return address;
}