我正在使用 jackson 2.10.0 ( https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.10.0 ),以下是一个简单的测试用例
Person类定义如下,对于setter,我使用了@JsonSetter注解,而对于getter没有使用@JsonGetter,
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
@JsonSetter("first_name")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
@JsonSetter("last_name")
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
然后,我创建一个 Person 对象,并将其序列化为字符串,
import com.fasterxml.jackson.databind.ObjectMapper;
public class Person3Test2 {
public static void main(String[] args) throws Exception {
Person p = new Person();
p.setFirstName("abc");
p.setLastName("def");
String str = new ObjectMapper().writeValueAsString(p);
System.out.println(str);
}
}
它将调用 Person 的 getter,因为它不使用 @JsonGetter,所以我认为输出应该是
{"firstName":"abc","lastName":"def"}
但是,我惊讶地发现它是:
{"first_name":"abc","last_name":"def"}
看来 @JsonSetter 影响了 getter 输出,我想问一下这里的行为是什么。
最佳答案
@JsonSetter
也会在序列化期间生效 here是 github 问题,如果您想要不同的名称,只需在 get
方法上使用另一个注释 @JsonGetter
Documentation may be wrong; @JsonSetter does not only affect deserialization. While it can indeed be used for asymmetric naming (similar to @JsonProperty itself with "split" annotation), its scope is not limited. It may have been at some point, but after unification of property handling (in 1.8 or so), there is less separation between various property accessors.
I can review Javadocs to make it clear that none of annotations is strictly limited in scope -- some may only be relevant to one or the other, but none is intentionally separated.
关于java - jackson @JsonGetter和@JsonSetter如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58600830/