[Java] Format and serialize nicely in Jackson

less than 1 minute read

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 it is a memo.

Serialize without formatting

A pattern that is serialized 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 and make the format beautiful 1

If you want to format for screen output and 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 format and make the format beautiful 2

If you want to display the array of elements with line breaks. For when elements are 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"
    ]
  }
}