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?
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.
Solution:
public class MyCustomClass {
@JsonProperty("users")
public LinkedHashMap<String, User> users;
@JsonProperty("jobs")
public ArrayList<Job> jobs;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With