jackson @JsonIgnore与@Getter注解

csga3l58  于 7个月前  发布在  其他
关注(0)|答案(5)|浏览(101)

我可以在lombok中使用@JsonIgnore和@Getter注解而不显式定义getter吗?因为我必须在序列化对象时使用这个JsonIgnore,但是在序列化时,JsonIgnore注解必须被忽略,所以我的对象中的字段不能为null?

@Getter
@Setter
public class User {

    private userName;

    @JsonIgnore
    private password;
}

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

qv7cva1a

qv7cva1a1#

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

@Getter
@Setter
public class User {

    private userName;

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

9rnv2umw2#

最近我在使用jackson-annotation 2. 9. 0和lombok1.18.2时也遇到了同样的问题
这就是我的工作:

@Getter
@Setter
public class User {

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

所以基本上添加注解@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)意味着该属性可能只为序列化而写(使用setter),但不会在序列化时读取(使用getter)。

h4cxqtbf

h4cxqtbf3#

这可能很明显,但我之前花了很多时间没有想到这个解决方案:

@Getter
@Setter
public class User {

    private userName;

    private password;

    @JsonIgnore
    public getPassword() { return password; }
}

正如塞巴斯蒂安所说,@__( @JsonIgnore )可以解决这个问题,但有时使用onX Lombok特性(@__())可能会产生副作用,例如破坏javadoc生成。

js5cn81o

js5cn81o4#

我最近有同样的问题。
有几种方法可以解决它:
1.在项目的根文件夹中创建文件lombok.config,其内容为:

// says that it's primary config (lombok will not scan other folders then)
config.stopBubbling = true

// forces to copy @JsonIgnore annotation on generated constructors / getters / setters
lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonIgnore
...

在你的类中,你可以像往常一样在字段级别上使用这个注解:

@JsonIgnore
private String name;

注意:如果您使用lombok @ RedArgsConstructor或@AllArgsConstructor,那么您应该使用@JsonIgnoreProperties删除所有@JsonIgnore的用法(如方案4所述,或者您仍然可以选择方案2或方案3)。这是必需的,因为@JsonIgnore注解不适用于构造函数参数。

1.手动定义Getter/Setter并在其上添加@JsonIgnore注解:

@JsonIgnore
public String getName() { return name; }

@JsonIgnore
public void setName(String name) { this.name = name; }

1.使用@JsonProperty(只读或只写,但不能同时使用):

@JsonProperty(access = JsonProperty.Access.READ_ONLY)  // will be ignored during serialization
private String name;

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)  // will be ignored during deserialization
private String name;

1.使用@JsonIgnoreProperties({ "fieldName1", "fieldName2", "..."})
我个人全局使用解决方案#1,当类也有注解@AllArgsConstructor@RequiredArgsConstructor时使用解决方案#4。

w8f9ii69

w8f9ii695#

使用JDK版本8时,请使用以下命令:

//  @Getter(onMethod=@__({@Id, @Column(name="unique-id")})) //JDK7
//  @Setter(onParam=@__(@Max(10000))) //JDK7
 @Getter(onMethod_={@Id, @Column(name="unique-id")}) //JDK8
 @Setter(onParam_=@Max(10000)) //JDK8

来源:https://projectlombok.org/features/experimental/onX

相关问题