jakartaee / jakartaee/jsonp-api
Provide API to define behavior of JsonObjectBuilder.add when value is null
- Dominant language
- Java
- Stars
- 160
- Forks
- 64
- Avg merge
- 4d 5h
- Merged PRs (30d)
- 4
Description
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
Contributor guide
Research direction
Start at JsonObjectBuilder and its add(...) overloads; verify the current null behavior against the three proposed modes. Done means an agreed API and coverage for ignoring null, serializing JsonValue.NULL, and preserving the exception as the default.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- api
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100