簡體   English   中英

如何將以下JSON打印為漂亮格式?

[英]How to print the following JSON to pretty format?

{ "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變量僅保存文件的單行,但是我希望整個文件以漂亮的格式打印。 我怎樣才能做到這一點 ? 這里的每一行都是一個單獨的實體。

根據您在評論中的回答,我認為它應該起作用:

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"
} ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM