I have this code that runs on Tomee with Jakarta EE 9.1, it is supposed to generate a JSON string taking the data from inputObj
. Problem is that there are fields with null values that are omitted from the resulting JSON even though withNullValues
is set to true. Any ideas what could be wrong?
JsonbConfig config = new JsonbConfig().withNullValues(true);
String json;
try (Jsonb jsonb = JsonbBuilder.create(config)) {
json = jsonb.toJson(inputObj);
}
3
Answers
Is it possible there are annotations on the fields of
inputObj
you are serializing that are overriding the.withNullValues(true)
setting?Ref: https://jakarta.ee/specifications/jsonb/3.0/jakarta-jsonb-spec-3.0.html#customizing-null-handling
I also found this: https://github.com/jakartaee/jsonb-api/issues/169#issuecomment-525387593
You didn’t share the class for
inputObj
but it seems to me like the only way this won’t work is if there are annotations on the fields in the class overriding the global setting inconfig
.I don’t know your full code, so this is my guess. If you don’t declare
getter
method for properties in class,Json-B
skips to serialize fields. Here is my example.Without Getter
Result when without getter
With Getter
Result when with getter
With public keyword
If you don’t use getter method for fields, fields should be public.
Result when with public
I hope this is helpful for you.
tl;dr; solved.
After I had read from your following comment, I solved your issue.
The annotation’s default
nillable
value isfalse
. To accomplish your request you need to make ittrue
as following.It yields something like
{... your other json fields, "test":null}
To begin, I have never used before this post JSON-B API. For you, I have installed it and its dependencies via its official webpage.
I have started a simple console app and created
pom.xml
to leverage its Maven dependencies as written on the webpage.I think your problem is as to the versions either that of its dependencies or directly its own version.
Don’t forget to reload project after changing any settings related to Maven.
What my
pom.xml
includes isAnd, when I run its official example which is
Dog
class in which I changed name of the dog tonull
, it works like a charm.Dog
classThe
Test
class in which the program begins to run