如何将以下JSON打印为漂亮格式?

时间:2018-12-05 10:03:00

标签: java json jackson

{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }

这是我的示例JSON,没有root标签。如何获取整个JSON并在每一行上对其进行迭代,然后将其存储为Java中的String对象并解析为JSON对象?我尝试了这段代码。

String file = "D:\\employees.json";
        ObjectMapper mapper = new ObjectMapper();
        String data = "";

        data = new String(Files.readAllBytes(Paths.get(file)));
        System.out.println(data);
        Object json = mapper.readValue(data, employees.class);
        System.out.println("JSON -> "+json);
        String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
        System.out.println(indented);

但是这里json变量仅保存文件的单行,但是我希望整个文件以漂亮的格式打印。我怎样才能做到这一点 ?这里的每一行都是一个单独的实体。

1 个答案:

答案 0 :(得分:1)

根据您对评论的回答,我认为它应该起作用:

String file = "here file path";
ObjectMapper mapper = new ObjectMapper();

List<Object> employeeList = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(file))) {
    employeeList.add(mapper.readValue(line, Object.class));
}

String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeList);
System.out.println(indented);

输出JSON看起来像这样:

[ {
  "firstName" : "John",
  "lastName" : "Doe"
}, {
  "firstName" : "Anna",
  "lastName" : "Smith"
}, {
  "firstName" : "Peter",
  "lastName" : "Jones"
} ]