I have a small function which takes an input JSON string, parses it using boon
into a Map
, replaces a value for a particular key, returns back the JSON string of the modified Map
.
The code is as follows:
// 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}]}
The problem is, when I do toJson(map)
it removes the key with null
values. So, if inputJson
contains a key with a null value, it doesn't appear in the output. (Notice: key1
is missing in the output)
How can I parse this without losing the null fields?
Using toJson you are using a default serialiser factory. From boon source code:
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());
}
....
)
Instead of using toJson try using a serialiser factory with includeNulls()
JsonSerializer factory = new JsonSerializerFactory().includeNulls().create();