使用@Getter注释@JsonIgnore

2022-09-01 11:29:25

我是否可以在不显式定义 getter 的情况下将@JsonIgnore与来自 lombok 的@Getter注释一起使用,因为我必须在序列化对象时使用此 JsonIgnore,但在反序列化时,必须忽略 JsonIgnore 注释,以便我的对象中的字段不能为 null?

@Getter
@Setter
public class User {

    private userName;

    @JsonIgnore
    private password;
}

我知道,只需在密码获取器上定义JsonIgnore,我就可以防止我的密码被序列化,但为此,我必须明确定义我不想要的getter。任何想法请, 任何帮助将不胜感激。


答案 1

要将@JsonIgnore放在生成的 getter 方法中,可以使用 onMethod = @__( @JsonIgnore )。这将生成具有特定注释的 getter。有关更多详细信息,请查看 http://projectlombok.org/features/GetterSetter.html

@Getter
@Setter
public class User {

    private userName;

    @Getter(onMethod = @__( @JsonIgnore ))
    @Setter
    private password;
}

答案 2

最近我遇到了同样的问题,使用杰克逊注释2.9.0和龙目岛1.18.2

这对我有用:

@Getter
@Setter
public class User {

    @JsonIgnore
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;

因此,基本上添加注释意味着该属性可能仅用于反序列化(使用 setter),但不会在序列化(使用 getter)时读取@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)