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?
As the wiki instructs, you need to register the corresponding module (in addition to any others you have):
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.registerModule(new JsonNullableModule());
Add the following configuration in Spring Boot:
@Configuration
public class JacksonConfiguration {
@Bean
public JsonNullableModule jsonNullableModule() {
return new JsonNullableModule();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With