Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson parsing JSON containing an array of objects and array of maps w/ dynamic keys

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?

like image 388
pat Avatar asked Jul 28 '13 03:07

pat


People also ask

What is dynamic JSON?

A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.


1 Answers

Solution:

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

    @JsonProperty("jobs")
    public ArrayList<Job> jobs;
}    
like image 112
pat Avatar answered Sep 18 '22 13:09

pat