how to map dynamic key in a json node to a class?

580 views Asked by At

I have a json like this,I have used to map this to a class using object mapper,where I have considered auth as JsonNode in the class UserData.java

    {
  "auth": [
    {
      "user_admin": [
        {
          "name": [
            "harry"
          ],
          "department": [
            "MC"
          ],
          "userid": [
            "1234"
          ]
        }
      ]
    },
    {
      "user_employee": [
        {
          "name": [
            "stella"
          ],
          "department": [
            "CC"
          ],
          "role": [
            "employee"
          ]
        }
      ]
    }
  ],
  "language":"english",
  "sub": "f598ab"

}

I have used json node for auth to map it to a class UserData.java as below.

 @Getter@Setter
    private JsonNode authorization;
    @Getter@Setter
    private String language;
     @Getter@Setter
    private String sub;

Now I want to map the values user_admin and user_employee which are dynamic to another class which will have name,department,userid. I have created a class auth.java and put this code in it.

 @Getter    @Setter
        private List< String> name;

        @Getter @Setter
        private List<String> department;

        @Getter @Setter
        private List<String> userid;
       @Getter  @Setter
       private List<String> role;

now I have tried the below code to map it,but its not working I am getting

UserData mappedObject=  (UserData)commonUtils.readJsonStringRespondToObjRequest((json), UserData.class);
Auth roleData=  mapper.treeToValue(mappedObject.getAuth(), Auth.class);

Error I got is

Can not deserialize instance of Auth.java out of START_ARRAY 
1

There are 1 answers

8
alayor On

Given that your JSON structure auth is an array you need to convert that into an array of Auth objects.

Auth[] roleData = mapper.treeToValue(mappedObject.getAuth(), Auth[].class);

Also, in your Auth class you should have these properties.

class Auth {
   @Getter @Setter
   UserAdmin user_admin;
   @Getter @Setter
   UserEmployee user_employee;
   @Getter @Setter
   String language;
   @Getter @Setter
   String sub;
}

Then, in UserAdmin and UserEmployee, you should have the fields corresponding to each property in JSON (name, department, etc).