Search code examples
javajsonnullobjectmapper

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

Solution

  • 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.