简体   繁体   English

ObjectMapper 未在文件中打印正确的 json

[英]ObjectMapper not printing correct json in file

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:我希望我的 outputFile 看起来完全像这样:

[
  {
    "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.我也尝试在 objectMapper 上使用漂亮的打印机,但结果是一样的。

You can customize indentation options of the DefaultPrettyPrinter using its methods indentObjectsWith() and indentArraysWith() .您可以使用DefaultPrettyPrinter的方法indentObjectsWith()indentArraysWith()自定义缩进选项。 Both expect an instance of Indenter interface.两者都需要Indenter接口的实例。 One of its implementations shipped with Jackson is DefaultIndenter . Jackson 附带的其中一个实现是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.当我们自定义DefaultPrettyPrinter时,应该指示ObjectMapper使用它进行序列化。

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

Finally, produce the JSON:最后,生成 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:考虑以下 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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM