Shape and serialize nicely with Jackson

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.

Serialize without formatting

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 shape and clean the format Part 1

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 shape and clean the format Part 2

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

Shape and serialize nicely with Jackson
What is Jackson?
What is Microservices? And Microservices Frameworks
Shape and serialize nicely with Jackson
[Java] What are overrides and overloads?
JSON with Java and Jackson Part 2 XSS measures
How to serialize and deserialize LocalDateTime type with GSON
[Java] JSON communication with jackson
URLSession with URLSession and Combine normally