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

mitkmikd  于 2022-12-10  发布在  Java
关注(0)|答案(1)|浏览(141)
ArrayList<ActionOutput> res = manager.getRes();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.writeValue(new File(args[1]), res);

我希望我的outputFile看起来完全像这样:

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

但它看起来像这样:

[ {                   <-- 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 }

我怎么能做到这一点呢?我也试着在objectMapper上使用漂亮的打印机,但结果是一样的。

ubof19bj

ubof19bj1#

您可以使用DefaultPrettyPrinter的方法indentObjectsWith()indentArraysWith()自定义缩进选项。这两个方法都需要Indenter接口的示例。Jackson附带的一个实现是DefaultIndenter

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

当我们定制了DefaultPrettyPrinter后,应该指示ObjectMapper使用它进行序列化。

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

最后,生成JSON:

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

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

这里有一个小的演示,说明缩进将被正确设置。
请考虑以下POJO:

public class ActionOutput {
    private String key1;
    private List<String> key2;
    private String key3;
    
    // all-args constructor, getters
}
  • 序列化示例:*
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);
  • 输出:*
[
  {
    "key1" : "value",
    "key2" : [ ],
    "key3" : null
  },
  {
    "key1" : "value",
    "key2" : [ ],
    "key3" : null
  }
]

相关问题