我想使用Jackson 2.9.x序列化以下POJO
static class MyData {
public Map<String, MyInnerData> members;
}
static class MyInnerData {
public Object parameters;
public boolean isPresent;
}
现在,如果我使用以下示例代码填充数据,如下所示:
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);
最终打印
{"members":{"data1":{"parameters":{"key-one":"val1","key-two":"val2","list":{"c1":"v1"}},"isPresent":true}}}
所需输出(相同的代码与Jackson 2.8.x提供正确的输出)
{"members":{"data1":{"parameters":{"key-one":"val1","key-null":null,"key-two":"val2","list":{"c1":"v1","c2":null}},"isPresent":true}}}
如果我在mapper上删除了setSerializationInclusion(JsonInclude.Include.NON_NULL),我会得到所需的输出,但ObjectMapper
的现有配置无法更改。我可以对POJO进行更改。
获得所需输出的最小变化是什么?
答案 0 :(得分:1)
您需要像下面这样配置对象:mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);