@JsonAutoDetect

2021-04-09

java

背叛就是脱离自己的位置,背叛,就是摆脱原位,投向未知。——米兰·昆德拉

我们在使用jackson时可能会用到这样一个注解

1
@JsonAutoDetect

例如我们这里一个Student

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
setterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
creatorVisibility = JsonAutoDetect.Visibility.NON_PRIVATE,
fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
private static class Student implements Serializable {
private static final long serialVersionUID = -3289647584974663707L;
public String name;
private Integer age;
private String job;
private GenderEnum gender;
private Date birthday;
private String json;
}

这里我们namepublic

我们指定了getterVisibilityJsonAutoDetect.Visibility.NONE

然后指定了fieldVisibilityJsonAutoDetect.Visibility.PUBLIC_ONLY

我们序列化一下

1
2
3
Instant from = LocalDateTime.parse("2021-01-09 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)).toInstant(ZoneOffset.MAX);
Student supa = Student.builder().name("supa").age(20).gender(GenderEnum.MALE).birthday(Date.from(from)).build();
System.out.println(new ObjectMapper().writeValueAsString(supa));

结果就只有一个name

image-20210412232536824

这里见名思意creatorVisibility就是构造器可见度setterVisibility就是setter可见度等

一般用于控制属性序列化可见度