Home > Blockchain >  ObjectMapper not printing correct json in file
ObjectMapper not printing correct json in file

Time:12-09

ArrayList<ActionOutput> res = manager.getRes();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.writeValue(new File(args[1]), res);

I expect my outputFile to look EXACTLY like this:

[
  {
    "key1": "value",
    "key2": [],
    "key3": null
  },
  {
    "key1": "value",
    "key2": [],
    "key3": null
  }
]

but it looks like this:

[ {                   <-- I need a newline after [
  "key1" : "value",
  "key2" : [ ],
  "key3" : null
}, {                  <-- I need a newline after },
  "key1" : "value",
  "key2" : [ ],       <-- no whitespace in empty array: [] instead of [ ]
  "key3" : null       <-- no whitespace after keys: "key3": null instead of "key3" : null
  } ]                 <-- I need a newline after }

How can I achieve this? I tried also to use pretty printer on objectMapper, but the result is the same.

CodePudding user response:

You can customize indentation options of the DefaultPrettyPrinter using its methods indentObjectsWith() and indentArraysWith(). Both expect an instance of Indenter interface. One of its implementations shipped with Jackson is DefaultIndenter.

DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentObjectsWith(new DefaultIndenter());
printer.indentArraysWith(new DefaultIndenter());

When we have customized the DefaultPrettyPrinter, ObjectMapper should be instructed to use it for serialization.

ObjectMapper mapper = new ObjectMapper();
mapper.setDefaultPrettyPrinter(printer);

Finally, produce the JSON:

ArrayList<ActionOutput> res = manager.getRes();

mapper
    .writerWithDefaultPrettyPrinter()
    .writeValue(new File(args[1]), res)

Here's a small demo illustrating that indentations would be set correctly.

Consider the following POJO:

public class ActionOutput {
    private String key1;
    private List<String> key2;
    private String key3;
    
    // all-args constructor, getters
}

Serialization example:

List<ActionOutput> actions = List.of(
    new ActionOutput("value", List.of(), null),
    new ActionOutput("value", List.of(), null)
);
        
String jsonRes = mapper
    .writerWithDefaultPrettyPrinter()
    .writeValueAsString(actions);
    
System.out.println(jsonRes);

Output:

[
  {
    "key1" : "value",
    "key2" : [ ],
    "key3" : null
  },
  {
    "key1" : "value",
    "key2" : [ ],
    "key3" : null
  }
]
  • Related