1

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?

3
  • 1
    Um, the same way you deal with any other null value? What do you mean specifically by "how do you deal?" Commented May 30, 2016 at 14:10
  • @RobertHarvey one may guess that the question is about how to switch between add and addNull depending on whether value is null or not (add would throw NPE if null). But it's unclear if this is the question or something else
    – gnat
    Commented May 30, 2016 at 14:16
  • Maybe you could subclass/wrap the builder, and add null checks in .add() that redirect to .addNull() if needed
    – Bwmat
    Commented May 11, 2019 at 20:01

4 Answers 4

3

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.

2
  • but what if you want to merge and overwrite an existing value? Commented Dec 8, 2020 at 22:34
  • Don’t merge JSON. Change your model objects, then create new JSON. If you MUST change JSON, then you either delete the existing key or add a key with a null value.
    – gnasher729
    Commented Jan 20, 2021 at 9:24
1

It is a JSON-B design deficiency. They could have done something slick like:

Json.createObjectBuilder().addIfNotNull("address", this.getAddress());

Json.createObjectBuilder().add("address", this.getAddress(), defaultOnNull);



0

It is possible to handle null, but this requires an explicit check, what beats the purpose, if you ask me. You can do this, thou:

String value;
// ...
return Json.createObjectBuilder()
    .add("my-key", value != null ? Json.createValue(value) : JsonValue.NULL)
    .build();

If you hoped for Json.createValue(String) to accept null strings, then you'll be disappointed as well.

-1

I fixed this "feature" and created this project https://github.com/leonardofel/JSON-java-put-null-fix

making the following code bellow possible:

    String v = null;
    JSONObject j = new JSONObject().put("myPreciousNull", v);
    System.out.println(j.toString());

prints:

    {"myPreciousNull":null}

just works !!!

Not the answer you're looking for? Browse other questions tagged or ask your own question.