简体   繁体   中英

How to print the following JSON to pretty format?

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

This is my sample JSON, not having root tag. How can I take the whole JSON and iterate over it for each line and store it as a String object in Java and parse as a JSON Object? I tried this code.

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);

But here the json variable is holding only single row of the file, but I want the entire file to be printed in pretty format. How can I do that ? Here every line is a separate entity.

Based on you answers in comments, I think it should work:

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);

Output JSON looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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