jsonp-api icon indicating copy to clipboard operation
jsonp-api copied to clipboard

Provide API to define behavior of JsonObjectBuilder.add when value is null

Open wesleyegberto opened this issue 6 years ago • 2 comments

Hi All I don't know if any one have already requested this (I couldn't find).

Would be nice to have a way to define the default behavior of the methods JsonObjectBuilder.add(Strig name, XXX value) when the received value is NULL.

3 behaviors could be provided:

  • Throw exception: current behavior, it should be default;
  • Ignore: the call wouldn't have any effect (just return);
  • Serialize null

Motivation

I often have to wrap the JsonObjectBuilder or create helper methods to handle the null value of my object. E.g.:

Json.createObjectBuilder()
    .add("nickname", Helper.emptyIfNull(person.getNickname()))
    .add("email", Helper.jsonNullIfNull(person.getEmail()))
    .build();
CustomObjectBuilder.from(Json.createObjectBuilder())
    .add("nickname", person.getNickname())
    .add("email", person.getEmail())
    .build();
JsonObjectBuilder builder = Json.createObjectBuilder();
if (person.getNickname() != null)
    builder.add("nickname", person.getNickname());
else
    builder.add("nickname", "");
if (person.getEmail() != null)
    builder.add("email", person.getEmail());

Proposal

Provide new methods on JsonObjectBuilder to define the behavior.

1 - Ignore null

This should set the JsonObjectBuilder to ignore the call when the value is null.

Code:

Json.createObjectBuilder()
    .ignoreNull()
    .add("name", "John Due")
    .add("nickname", null)
    .build();

Expected output:

{
  "name": "John Due"
}

2 - Serialize null

This should set the JsonObjectBuilder to serialize the JsonValue.NULL when the value is null.

Code:

Json.createObjectBuilder()
    .serializeNull()
    .add("name", "John Due")
    .add("nickname", null)
    .build();

Expected output:

{
  "name": "John Due",
  "nickname": null
}

3 - Throw exception

This is the current behavior and should be the default behavior to keep compatibilities.

Code:

Json.createObjectBuilder()
    .forbidNull()
    .add("nickname", null)
    .build();

Expected: NullPointerException

This is something I miss on Json-P because I use it often to avoid DTO.

Thank you

wesleyegberto avatar Jul 07 '18 19:07 wesleyegberto