Ori Marko
Ori Marko

Reputation: 58822

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;
}

Upvotes: 4

Views: 16987

Answers (2)

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.

Upvotes: 3

Emre Savcı
Emre Savcı

Reputation: 3070

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.

Upvotes: 4

Related Questions