I'm trying to use JsonNullable<String>
to distinguish between the absence of a value and null
. When I serialize my Java object, User
, the JsonNullable<String>
field is serialized as a JSON object with value
{"present":false}
I'm expecting it to print {}
since I initialized the field with undefined
.
Here's my class
public class User {
@JsonProperty("userId")
private JsonNullable<String> userId = JsonNullable.undefined();
//set and get
//tostring
}
and a small driver program where I actually set a value within the JsonNullable
field.
User user = new User();
user.setUserId(JsonNullable.of("12345"));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());
String expectedData = objectMapper.writeValueAsString(user);
System.out.println(expectedData);
This prints
{"userId":{"present":true}}
But I expected
{"userId":"12345"}
In other words, I expected the value wrapped within the JsonNullable
to be serialized into the JSON. Why are JsonNullable
and Jackson behaving this way?