8

I have json like this:

{

    "users":{
           "1234":{
                 "firstname":"Joe",
                 "lastname":"Smith"
           },
           "9876":{
                 "firstname":"Bob",
                 "lastname":"Anderson"
           }
    },
    "jobs":[
          {
              "id":"abc",
              "location":"store"
          },
          {
              "id":"def",
              "location":"factory"
          }
    ]
}

I'm parsing this using Jackson and so I have been parsing responses using: readvalue(json, MyCustomClass.class)

Where MyCustomClass looks like

public class MyCustomClass{
      @JsonProperty("jobs")
      ArrayList<Job> jobs;

      @JsonProperty("users")
      ArrayList<UserMap> usersMap;
}

Now the jobs parse perfectly into Jobs objects but I can't get the users to parse since they have dynamic keys. I read about JsonAnyGetter/Setter and tried making the UserMap object map that maps a string -> User like:

public class UserMap {

private HashMap<String,User> usersMap;


@JsonAnySetter
public void add(String key, User user){
    usersMap.put(key, user);
}

@JsonAnyGetter
public Map<String, User> getUsersMap(){
    return usersMap;
}


}

but that doesn't work. I think I can do it with a TypeReference wrapper but I only can think of a way to do that if those maps were the only type I was getting back. Since I am getting different types back (users and jobs) is it possible to do this?

pat
  • 1,005
  • 4
  • 12
  • 29

2 Answers2

11

Solution:

public class MyCustomClass {
    @JsonProperty("users")
    public LinkedHashMap<String, User> users;

    @JsonProperty("jobs")
    public ArrayList<Job> jobs;
}    
pat
  • 1,005
  • 4
  • 12
  • 29
0

You could probably get around this by writing your own custom deserializer and register it with the object mapper that you are using. This should work as you will have complete control of how each object is deserialized into a User object.

See this jackson documentation on how to roll your own deserializer.

Would also like to say, if you have control over the json structure - I would change the key value (which I am guessing is an ID for the user) to be a part of the actual json object as opposed to being the key. This will help you avoid the issue all together.

For example:

"users":{
       {
             "id":"1234",
             "firstname":"Joe",
             "lastname":"Smith"
       },
       {
             "id":"9876",
             "firstname":"Bob",
             "lastname":"Anderson"
       }     
Eggman87
  • 571
  • 5
  • 12