问题描述
我有这样的json:
{
"users":{
"1234":{
"firstname":"Joe",
"lastname":"Smith"
},
"9876":{
"firstname":"Bob",
"lastname":"Anderson"
}
},
"jobs":[
{
"id":"abc",
"location":"store"
},
{
"id":"def",
"location":"factory"
}
]
}
我正在使用Jackson进行解析,因此我一直在使用以下方法来解析响应:readvalue(json,MyCustomClass.class)
I'm parsing this using Jackson and so I have been parsing responses using: readvalue(json, MyCustomClass.class)
MyCustomClass的外观
Where MyCustomClass looks like
public class MyCustomClass{
@JsonProperty("jobs")
ArrayList<Job> jobs;
@JsonProperty("users")
ArrayList<UserMap> usersMap;
}
现在,作业可以完美地解析为Jobs对象,但是我无法让用户解析,因为它们具有动态键.我读到有关JsonAnyGetter/Setter的内容,并尝试制作映射字符串的UserMap对象映射->用户,如:
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;
}
}
但这不起作用.我想我可以使用TypeReference包装器来做到这一点,但是如果那些映射是我返回的唯一类型,那么我只能想到一种方法.由于我回来了不同的类型(用户和工作),是否可以这样做?
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?
推荐答案
解决方案:
public class MyCustomClass {
@JsonProperty("users")
public LinkedHashMap<String, User> users;
@JsonProperty("jobs")
public ArrayList<Job> jobs;
}
这篇关于Jackson解析JSON,其中包含对象数组和带有动态键的地图数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!