[英]Jackson serialization with including null values for Map
I've the following POJOs that I want to serialize using Jackson 2.9.x 我要使用Jackson 2.9.x序列化以下POJO
static class MyData {
public Map<String, MyInnerData> members;
}
static class MyInnerData {
public Object parameters;
public boolean isPresent;
}
Now if I populate the data with the following sample code as shown: 现在,如果我使用以下示例代码填充数据,如下所示:
Map<String, Object> nodeMap = new LinkedHashMap<>();
nodeMap.put("key-one", "val1");
nodeMap.put("key-null", null);
nodeMap.put("key-two", "val2");
Map<String, Object> child1 = new LinkedHashMap<>();
child1.put("c1", "v1");child1.put("c2", null);
nodeMap.put("list", child1);
MyInnerData innerData1 = new MyInnerData();
innerData1.parameters = nodeMap;
innerData1.isPresent = true;
MyData myData = new MyData();
myData.members = new LinkedHashMap<>();
myData.members.put("data1", innerData1);
// serialize the data
ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
String actual = mapper.writeValueAsString(myData);
System.out.println(actual);
This ends up printing 这样结束打印
{"members":{"data1":{"parameters":{"key-one":"val1","key-two":"val2","list":{"c1":"v1"}},"isPresent":true}}}
Desired Output (same code gives correct output with Jackson 2.8.x ) 所需的输出(相同的代码可在Jackson 2.8.x中提供正确的输出)
{"members":{"data1":{"parameters":{"key-one":"val1","key-null":null,"key-two":"val2","list":{"c1":"v1","c2":null}},"isPresent":true}}}
If I remove the setSerializationInclusion(JsonInclude.Include.NON_NULL) on the mapper, I get the required output but the existing configuration for the ObjectMapper
cant be changed. 如果删除映射器上的setSerializationInclusion(JsonInclude.Include.NON_NULL),则会得到所需的输出,但是ObjectMapper
的现有配置无法更改。 I can make changes to the POJO however. 我可以对POJO进行更改。
What would be the least change to get the desired output? 要获得所需的输出,最小的变化是什么?
您需要这样配置您的对象: mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.