[英]Use of Jackson: get duplicated fields in json string
I have a POJO with Jackson annotations: 我有一个带有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;
}
}
Then I created a Person
instance & parse it to json string: 然后,我创建了一个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);
But the json string ( personJson
) I got is the following: 但是我得到的json字符串( personJson
)如下:
{"first_name":"John","last_name":"Smith","firstName":"John","lastName":"Smith"}
Why I get duplicated fields " first_name
" & " firstName
", so to " last_name
" & " lastName
" in JSON string? 为什么我得到重复的字段“ first_name
”和“ firstName
”,以至于JSON字符串中的“ last_name
”和“ lastName
”?
===== UPDATE === =====更新===
I also tried : 我也尝试过:
Annotation: 注解:
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
ObjectMapper: ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE);
But I still get the duplicated attributes in JSON in some other POJO... 但是我仍然在其他一些POJO中得到JSON中的重复属性...
I managed to solve the problem myself. 我设法自己解决了这个问题。
The reason why I still got duplicated fields in JSON after the UPDATE is that there are boolean properties in my other POJO which yields the accessor methods starting with " is " , eg: 我在UPDATE之后仍然在JSON中重复字段的原因是,我的其他POJO中存在布尔属性,该属性产生以“ is ”开头的访问器方法,例如:
public class Other {
@JsonProperty("money_paid")
private boolean moneyPaid;
public boolean isMoneyPaid() {
return moneyPaid;
}
...
}
So, the generated json contained {money_paid:true, moneyPaid:true}. 因此,生成的json包含{money_paid:true,moneyPaid:true}。 To get rid of it, I just added one more restriction on mapper
when setVisibilityChecker
, which is: 为了摆脱它,我刚在setVisibilityChecker
时对mapper
增加了一个限制,即:
.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.