Jackson扁平化处理对象
普通对象
一般不对对象进行扁平化处理的化是以下格式的,我们不需要显示password和userInfo
{
"password": {
"salt": "sdsdcx",
"password": "12sadtg32"
},
"userInfo": {
"name": "lyra",
"age": 12
}
}
业务需要的格式是不加password和userInfo的扁平对象,如下json所示
{
"salt": "sdsdcx",
"password": "12sadtg32",
"name": "lyra",
"age": 12
}
这时候可以使用在实体类的成员变量中添加Jackson的JsonUnwrapped
注解即可
如下代码所示
public class User {
@JsonUnwrapped
private Password password;
@JsonUnwrapped
private UserInfo userInfo;
public Password getPassword() {
return password;
}
public void setPassword(Password password) {
this.password = password;
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
}
运行后就返回扁平对象了
map
JsonUnwrapped
注解是不支持Map对象
有的使用map返回的json是以下格式的
{
"student": {
"0": {
"id": 0,
"name": "lyra",
"age": 21
},
"1": {
"id": 1,
"name": "lyra",
"age": 21
},
"2": {
"id": 2,
"name": "lyra",
"age": 21
}
}
}
我们希望是对象紧接着对象,student名称是不需要的,根据StackOverflow的这篇文章,添加map的注解方法即可解决
https://stackoverflow.com/questions/18043587/why-im-not-able-to-unwrap-and-serialize-a-java-map-using-the-jackson-java-libra
public class Grade {
private Map<String, User> student;
@JsonAnySetter
public void addStudent(String key, User value) {
student.put(key, value);
}
@JsonAnyGetter
public Map<String, User> getStudent() {
return student;
}
public void setStudent(Map<String, User> student) {
this.student = student;
}
}
需要注意的是这三部分要保证一致
之后返回的json结果为
{
"0": {
"id": 0,
"name": "lyra",
"age": 21
},
"1": {
"id": 1,
"name": "lyra",
"age": 21
},
"2": {
"id": 2,
"name": "lyra",
"age": 21
}
}
虽然道路是曲折的,但前途是光明的。