Search code examples
javajsondata-structuresjax-rsdto

What is the best way to write java DTO for dynamic json keys


I am writing a jax-rs based rest API where my response would contain dynamic json keys. In the response below json keys Tom, Harry are dynamic and there can be many more. What would be the best way to write a java DTO to represent structure and be able have dynamic employee names?

    "employee":{  
      "Tom":{  
         "id":"23974",
         "name":"Tom L",
         "jobRole":"Associate",
         "contact":{  
            "phone":"8889993332",
            "address":"some address"
         },
         "peers":[  
            "peer1",
            "peer2"
         ]
      },
      "Harry":{  
         "id":"34234",
         "name":"Harry S",
         "jobRole":"Associate",
         "contact":{  
            "phone":"3459993332",
            "address":"some address"
         },
         "peers":[  
            "peer1",
            "peer2"
         ]
      }
   }
}

Solution

  • I would recommend the below class:

    class EmployeeDetails {
          private Map<String, Employee> Employee;
    }
    
    class Employee {
         private Long id;
         private String name;
         private String jobRole;
         private Contact contact;
         private List<String> peers;
     }
    
     class Contact {
        private String phone;
        private String address;
      }