Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@JsonIgnore with @Getter Annotation

Can I use @JsonIgnore with @Getter annotation from lombok without explicitly define the getter, because I have to use this JsonIgnore while serializing the object but while deserializing, the JsonIgnore annotation must be ignored so the field in my object must not be null?

@Getter @Setter public class User {      private userName;      @JsonIgnore     private password; } 

I know, just by define the JsonIgnore on the getter of password I can prevent my password to be serialized but for that, I have to explicitly define the getter thing that I don't want. Any idea please, Any help will be appreciated.

like image 590
Prateek Jain Avatar asked Jun 28 '14 11:06

Prateek Jain


People also ask

What is the use of @JsonIgnore annotation?

@JsonIgnore is used at field level to mark a property or list of properties to be ignored.

What is the use of @JsonIgnore annotation in spring boot?

@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setters, getters or fields. If you add @JsonIgnore to a field or its getter method, the field is not going to be serialized.

Where should I put JsonIgnore?

@JsonIgnore annotation is used to ignore fields from de-serialization and serialization, it can be put directly on the instance member or on its getter or its setter.

How do I ignore a JSON property?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.


2 Answers

To put the @JsonIgnore to the generated getter method, you can use onMethod = @__( @JsonIgnore ). This will generate the getter with the specific annotation. For more details check http://projectlombok.org/features/GetterSetter.html

@Getter @Setter public class User {      private userName;      @Getter(onMethod = @__( @JsonIgnore ))     @Setter     private password; } 
like image 157
Sebastian Avatar answered Sep 19 '22 22:09

Sebastian


Recently i had the same issue using jackson-annotation 2.9.0 and lombok 1.18.2

This is what worked for me:

@Getter @Setter public class User {      @JsonIgnore     @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)     private String password; 

So basically adding the annotation @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) means that the property may only be written for deserialization (using setter) but will not be read on serialization (using getter)

like image 42
damato Avatar answered Sep 20 '22 22:09

damato