jakartaee / jakartaee/jsonp-api

[spec] introduce null-save JsonObjectBuilder.add and JsonGenerator.write methods

Open
#213 3 comments 2 reactions 1 assignee Claimed by @m0mus View on GitHub
Dominant language
Java
Stars
160
Forks
64
Avg merge
4d 5h
Merged PRs (30d)
4

Description

I'm missing a set of methods in both JsonGenerator and JsonObjectBuilder to fluently deal with null values.
E.g. if you look at JsonObjectBuilder.add [1] then you'll notice that it throws a NullPointerException if the value is null.

This is sometimes a bit inconvenient. Especially if one wants to represent some information from a DTO or entity into JSON. Note that JSON-B is out or scope for my use case.
Such a code has to check every single attribute and either use `addNull` (resp writeNull) or skip the whole attribute if the value is null. This destroys the fluentness of the whole API.
Also note that some methods like `JsonGenerator#write(String, String)` [2] are not defined to throw a NullPointerException in case the value is null. But with others like `write(String, int)` the NPE already happens during auto-boxing.

I'd rather prefer to have `JsonGenerator#write*` and `JsonObjectBuilder#add*` consistently throw NPE, but have an additional set of methods with `optionalAdd(String key, Integer value, boolean skipIfNull)`

That way we would end up with something like:
```
jsonObjectBuilder
.add("id", person.getId()) // mandatory
.optionalAdd("name", person.getName(), true)
.optionalAdd("age", person.getAge(), true)
.build();
```

And similar methods for `JsonGenerator#optionalWrite(...)`

[1] https://javaee.github.io/javaee-spec/javadocs/javax/json/JsonObjectBuilder.html#add-java.lang.String-java.lang.String-
[2] https://javaee.github.io/javaee-spec/javadocs/javax/json/stream/JsonGenerator.html#write-java.lang.String-java.lang.String-

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.