Home > Software design >  @JSON annotation to replace a String value with null in Java
@JSON annotation to replace a String value with null in Java

Time:02-25

I am looking for an annotation I can use to replace String value to null in Java

There are some @Json annotation that can do customization while serializing a JSON object to POJO,

I want to do something like this:

@JsonFormat(<if incoming value is SOMESTRING>, <set incoming value to null>)
String valueChangedUsingAnnotation;

CodePudding user response:

Use @JsonIgnore annotation. This annotation is used when you want to ignore certain properties of a java class. It will ignore those fields annotated with when reading from json to java object and also, writing java object to json.

CodePudding user response:

If incoming value is SOMETHING, set its value to null. For this you can update the setter method of that particular field in POJO class. Because, when incoming object is deserialized it invokes setter methods of each fields.

Something like below:

class Test{

//constructor, other fields and their getters and setters

private String target;

public void setTarget(String target) {
if(target.equals("abcd"){
   this.target=null
}
else {
    this.target=target;
  } 
} 
} 

There is no need of any JSON annotations.

  • Related