我有一个小函数,它接受输入的JSON字符串,使用boon
解析为Map
,替换特定键的值,返回修改后的Map
的JSON字符串。
代码如下:
// 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
包含具有空值的键,则它不会出现在输出中。 (注意:输出中缺少key1
)我该如何解析而不丢失空字段?
最佳答案
使用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();
关于java - Java boon JSON解析器从输出中删除空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42125603/