When I want to serialize to JSON in Java, I often use Jackson because JSON-B is not powerful enough, but I always forget how to write it, so make a note.
A pattern that serializes without formatting for data exchange. Usually this.
var item = Map.of("parent", Map.of("child", List.of("a", "b", "c")));
var json = new ObjectMapper().writeValueAsString(item);
result
{"parent":{"child":["a","b","c"]}}
If you want to format it for screen output or configuration files. Use INDENT_OUTPUT
var item = Map.of("parent", Map.of("child", List.of("a", "b", "c")));
var mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
var json = mapper.writeValueAsString(item);
result
{
"parent" : {
"child" : [ "a", "b", "c" ]
}
}
If you want to display an array of elements with line breaks. For when the element is long. Use PrettyPrinter and SYSTEM_LINEFEED_INSTANCE.
var item = Map.of("parent", Map.of("child", List.of("a", "b", "c")));
var printer = new DefaultPrettyPrinter();
printer.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
var json = new ObjectMapper().writer(printer).writeValueAsString(item);
result
{
"parent" : {
"child" : [
"a",
"b",
"c"
]
}
}
Recommended Posts