Jackson parsing JSON containing an array of objects and an array of maps with 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 parse this with Jackson, so I parsed the answers using: readvalue (json, MyCustomClass.class)

Where MyCustomClass looks like

 public class MyCustomClass{ @JsonProperty("jobs") ArrayList<Job> jobs; @JsonProperty("users") ArrayList<UserMap> usersMap; } 

Now the tasks are well versed in Jobs' objects, but I can not get users to understand, since they have dynamic keys. I read about JsonAnyGetter / Setter and tried to create a UserMap object map that displays a line -> 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 will not work. I think I can do this with the TypeReference shell, but I can only think about how to do this if these cards were the only type I returned. Since I get different types back (users and jobs), can this be done?

+6
source share
2 answers

Decision:

 public class MyCustomClass { @JsonProperty("users") public LinkedHashMap<String, User> users; @JsonProperty("jobs") public ArrayList<Job> jobs; } 
+9
source

You could get around this by writing your own deserializer and registering it using the mapper object you are using. This should work as you will have full control over how each object is deserialized into a User object.

See this Jackson documentation on how to collapse your own deserializer.

I would also like to say that if you have control over the json structure - I would change the key value (which I guess is the identifier for the user) to be part of the real json object, and not be the key. This will help you avoid the problem together.

For instance:

 "users":{ { "id":"1234", "firstname":"Joe", "lastname":"Smith" }, { "id":"9876", "firstname":"Bob", "lastname":"Anderson" } 
0
source

Source: https://habr.com/ru/post/950445/


All Articles