gpt4 book ai didi

java - 包含 Map 空值的 Jackson 序列化

转载 作者:行者123 更新时间:2023-11-29 04:22:30 32 4
gpt4 key购买 nike

我有以下 POJO,我想使用 Jackson 2.9.x 序列化

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}}}

如果我删除映射器上的 setSerializationInclusion(JsonInclude.Include.NON_NULL),我会得到所需的输出,但无法更改 ObjectMapper 的现有配置。不过,我可以对 POJO 进行更改。

获得所需输出的最少更改是什么?

最佳答案

您需要像这样配置您的对象:mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);

关于java - 包含 Map 空值的 Jackson 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222055/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com