Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectMapper - How to send null value in JSON

According to third party API spec, I need to send null value in JSON using ObjectMapper if no value exists,

Expected results : "optional": null

If optional value exists, then send "optional": "value"

I didn't find such option in Jackson – Working with Maps and nulls

Code:

requestVO = new RequestVO(optional);
ObjectMapper mapper = new ObjectMapper();
String requestString = mapper.writeValueAsString(requestVO);

Class:

public class RequestVO {
   String optional;
   public RequestVO(String optional) {
      this.optional = optional;
   }

public String getOptional() {
    return optional;
}

public void setOptional(String optional) {
    this.optional= optional;
}
like image 599
user7294900 Avatar asked Oct 21 '25 10:10

user7294900


2 Answers

Add @JsonInclude(JsonInclude.Include.USE_DEFAULTS) annotation to your class.

@JsonInclude(JsonInclude.Include.USE_DEFAULTS)
class RequestVO {
    String optional;

    public RequestVO(String optional) {
        this.optional = optional;
    }

    public String getOptional() {
        return optional;
    }

    public void setOptional(String optional) {
        this.optional = optional;
    }
}

Example :

RequestVO requestVO = new RequestVO(null);

ObjectMapper mapper = new ObjectMapper();
try {
    String requestString = mapper.writeValueAsString(requestVO);
    System.out.println(requestString);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

Output :

{"optional":null}

With value:

RequestVO requestVO = new RequestVO("test");

ObjectMapper mapper = new ObjectMapper();
try {
    String requestString = mapper.writeValueAsString(requestVO);
    System.out.println(requestString);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

Output:

{"optional":"test"}

You can use @JsonInclude annotation on even properties. So, this way you can either serialize as null or ignore some of the properties while serializing.

like image 147
Emre Savcı Avatar answered Oct 23 '25 01:10

Emre Savcı


You can configure your ObjectMapper this way:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

If no value is present on the JSON request your processed will have a null as you expected.

You can even configure a Spring bean for the ObjectMapper if you need.

EDIT:

I misunderstood the question, he was interested on the JSON response and not on the object parsed. The correct property is this case is JsonInclude.Include.USE_DEFAULTS.

Apologies for the confusion.

like image 25
Táizel Girão Martins Avatar answered Oct 23 '25 01:10

Táizel Girão Martins