我有一个小函数,它接受一个输入JSON字符串,使用boon
将其解析为Map
,替换特定键的值,返回修改后的{{1的JSON字符串}}。
代码如下:
Map
问题是,当我执行// inputJson = {"key3":"A","key2":"B","key1":null,"keyX":[{"x":2019,"y":123,"z":456},{"x":2017,"y":234,"z":345},{"x":2018,"y":456,"z":567}]}
private static String sorter(String inputJson) {
JsonParserAndMapper mapper = new JsonParserFactory().strict().create();
Map<String, Object> map = mapper.parseMap(inputJson);
List<?> l1 = (List<?>) map.get("keyX");
sort(l1, Sort.sortBy("x"));
map.replace("keyX", l1);
for (String x: map.keySet())
System.out.println(map.get(x));
String outputJson = toJson(map); // problem seems to be here
return outputJson
// outputJson = {"key2":"B","key3":"A","keyX":[{"x":2017,"y":234,"z":345},{"x":2018,"y":456,"z":567},{"x":2019,"y":123,"z":456}]}
时,会删除包含toJson(map)
值的密钥。因此,如果null
包含具有空值的键,则它不会出现在输出中。 (注意:输出中缺少inputJson
)
如何在不丢失空字段的情况下解析它?
答案 0 :(得分:2)
使用toJson您正在使用默认的序列化工厂。来自boon源代码:
public class JsonFactory {
private static ObjectMapper json = JsonFactory.create();
public static ObjectMapper create () {
JsonParserFactory jsonParserFactory = new JsonParserFactory();
jsonParserFactory.lax();
return new ObjectMapperImpl(jsonParserFactory, new JsonSerializerFactory());
}
....
)
而不是使用toJson尝试使用带有includeNulls()
的序列化工厂JsonSerializer factory = new JsonSerializerFactory().includeNulls().create();