Java JSON – How to Handle NULL Values When Creating JsonObject

javajson

I am learning Java and JSR-353. My question is quite forward.
Having the method below:

public JsonObject createJsonObject() {
    return Json.createObjectBuilder()
            .add("address", this.getAddress())
            .add("city", this.getCity())
            .add("state", this.getState())
            .add("postalcode", this.getPostalcode())
            .add("country", this.getCountry())
            .add("contactNumber", this.getContactNumber())
            .add("secondContactNumber",this.getSecondContactNumber())
            .build();
}

How do you deal if any of the attributes is NULL?

Best Answer

In a JSON "object" (aka dictionary), there are two ways to represent absent values: Either have no key/value pair at all, or have a key with the JSON value null.

So you either use .add with a proper value what will get translated to null when you build the JSON, or you don't have the .add call.