问题
I am using Jackson to serialize some beans into JSON, inside an application that is using Spring Boot 1.5.
I noticed that to serialize a bean using the @JsonCreator
correctly, I have to declare the getter method for each property, plus the @JsonProperty
annotation.
public class Person {
private final String name;
private final int age;
@JsonCreator
public Person(@JsonProperty("name") String name,
@JsonProperty("age") int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
If I remove methods getName
and getAge,
Jackson does not serialize the associated propertiy. Why does Jackson also need the getter methods?
回答1:
Jackson uses reflection to access private and protected properties.
As soon as you delete the getter, Jackson doesn't know how to serialize/deserialize the properties (=your private fields).
The used @JsonProperty
annotations of the constructor won't help Jackson to find the properties while compile time as your constructor will be used at runtime.
Unintuitively, the getter also makes the private field deserializable as well – because once it has a getter, the field is considered a property.
Paraschiv, Eugen - "Jackson – Decide What Fields Get Serialized/Deserialized"
来源:https://stackoverflow.com/questions/49800779/jackson-also-needs-getter-methods-to-correctly-serialize-a-bean-property-using