我有一个带Jackson注释的POJO:
public class Person {
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
然后我创建了一个Person
实例&将其解析为json字符串:
Person p = new Person();
p.setFirstName("John");
p.setLastName("Smith");
//parse to json string
ObjectMapper mapper = new ObjectMapper();
String personJson = mapper.writeValueAsString(p);
但我得到的json字符串(personJson
)如下:
{"first_name":"John","last_name":"Smith","firstName":"John","lastName":"Smith"}
为什么我会获得重复的字段“first_name
”& “firstName
”,以及“last_name
”& JSON字符串中的“lastName
”?
=====更新===
我也尝试过:
注释:
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE);
但我仍然在其他一些POJO中获得JSON中的重复属性......
答案 0 :(得分:4)
我自己设法解决了这个问题。
我在UPDATE之后仍然在JSON中有重复字段的原因是我的另一个POJO中存在布尔属性,这产生了以&#34开头的访问器方法; 是" , e.g:
public class Other {
@JsonProperty("money_paid")
private boolean moneyPaid;
public boolean isMoneyPaid() {
return moneyPaid;
}
...
}
因此,生成的json包含{money_paid:true,moneyPaid:true}。为了摆脱它,我在mapper
setVisibilityChecker
时添加了一个限制,这是:{/ p>
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)