com.fasterxml.jackson---04_如何去除getter和setter
程序员文章站
2024-02-04 13:44:34
...
纯粹地为了技术方面的原因而添加getter和setter是不好的,可以通过以下方式去除掉对getter和setter的依赖:
objectMapper.setVisibility(ALL, NONE)
.setVisibility(FIELD, ANY);
ObjectMapper将通过反射机制直接操作Java对象上的字段。
此时创建Person如下:
public class Person {
private String name;
private String address;
private String mobile;
public Person(String name, String address, String mobile) {
this.name = name;
this.address = address;
this.mobile = mobile;
}
}
序列化Person:
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(ALL, NONE)
.setVisibility(FIELD, ANY);
Person person = new Person("name", "address", "mobile");
System.out.println(objectMapper.writeValueAsString(person));
}
然而,此时反序列化的时候报错:
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.shell.b2b.factory.model.Person` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
这是因为ObjectMapper在为字段设值之前,无法初始化Person对象,此时有两种解决方式:
1、为Person增加默认构造函数:
private Person() {
}
请注意,此时请将该构造函数设置为private的,因为我们不想因为纯技术原因而向外暴露一个会将Person类置于非法状态的构造函数(一个没有名字的Person还有什么用?)。
2、在已有构造函数上加上@JsonCreator
注解,通常与@JsonProperty
一起使用:
@JsonCreator
public Person(@JsonProperty("name") String name,
@JsonProperty("address") String address,
@JsonProperty("mobile") String mobile) {
this.name = name;
this.address = address;
this.mobile = mobile;
}