gpt4 book ai didi

java - 使用 jackson : get duplicated fields in json string

转载 作者:行者123 更新时间:2023-11-30 07:09:42 25 4
gpt4 key购买 nike

我有一个 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”和“lastName”在JSON字符串中?

=====更新===

我也试过:

注释:

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)

对象映射器:

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 中的重复属性...

最佳答案

我设法自己解决了这个问题。

在 UPDATE 之后我仍然在 JSON 中得到重复字段的原因是我的其他 POJO 中有 boolean 属性,它产生以 "is"开头的访问器方法,例如:

public class Other {
@JsonProperty("money_paid")
private boolean moneyPaid;

public boolean isMoneyPaid() {
return moneyPaid;
}
...
}

因此,生成的 json 包含 {money_paid:true, moneyPaid:true}。为了摆脱它,我只是在 setVisibilityChecker 时对 mapper 添加了一个限制,即:

.withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)

关于java - 使用 jackson : get duplicated fields in json string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com