问题描述
我正在尝试使用JsonNullable<String>
来区分缺少值和null
.当我序列化Java对象User
时,JsonNullable<String>
字段被序列化为带有值的JSON对象
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}
由于我使用undefined
初始化了该字段,因此我希望它能打印{}
.
I'm expecting it to print {}
since I initialized the field with undefined
.
这是我的课程
public class User {
@JsonProperty("userId")
private JsonNullable<String> userId = JsonNullable.undefined();
//set and get
//tostring
}
和一个小的驱动程序,我实际上在JsonNullable
字段中设置了一个值.
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);
此打印
{"userId":{"present":true}}
但是我期望
{"userId":"12345"}
换句话说,我希望包装在JsonNullable
中的值可以序列化到JSON中.为什么JsonNullable
和Jackson表现出这种方式?
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?
推荐答案
作为 Wiki 指示,您需要注册相应的模块(除了您拥有的其他模块之外):
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());
这篇关于JsonNullable并未与Jackson连载其价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!