Pretty-Print JSON in Java

Pretty-Print JSON in Java

Google's GSON can do this in a nice way:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonString);
String prettyJsonString = gson.toJson(je);

or since it is now recommended to use the static parse method from JsonParser you can also use this instead:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement je = JsonParser.parseString​(uglyJsonString);
String prettyJsonString = gson.toJson(je);

Here is the import statement:

import com.google.gson.*;

Here is the Gradle dependency:

implementation 'com.google.code.gson:gson:2.8.7'

Best way to make JSON pretty in Java

I think the best way beautify the json string is as follows using Jackson:

import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject)

Convert JSON String to Pretty Print JSON output using Jackson

To indent any old JSON, just bind it as Object, like:

Object json = mapper.readValue(input, Object.class);

and then write it out with indentation:

String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

this avoids your having to define actual POJO to map data to.

Or you can use JsonNode (JSON Tree) as well.

How do I pretty-print existing JSON data with Java?

I think for pretty-printing something, it's very helpful to know its structure.

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

Java Json pretty print javax.json

You should be using JsonWriter instead of JsonGenerator.

Replace these lines:

JsonGeneratorFactory jf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jf.createGenerator(sw);

jg.write(jobj).close();

with these:

JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
JsonWriter jsonWriter = writerFactory.createWriter(sw);

jsonWriter.writeObject(jobj);
jsonWriter.close();

Writing JSON file with pretty print

As Nivas said in the comments, some programs strip newlines, so viewing the output in those programs (such as Notepad) could make them look "ugly". Make sure you are viewing them in a program that displays newlines correctly, such as Notepad++.

json file I/O with pretty print format using gson in java?

As you are new, I'll quickly walk you through the process of writing a List of Employee objects to a JSON file with pretty printing:

Step 1: Create a method that takes in a List and a String filePath:

public void jsonWriter(List<Employee> employees, String filePath)

Step 2: Build a Gson Object with pretty printing enabled:

Gson gson = new GsonBuilder().setPrettyPrinting().create();

Step 3: Write your List<Employee> to a JSON file in the given filePath using a FileWriter:

       try(FileWriter writer = new FileWriter(filePath)) {
gson.toJson(employees, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

Finally the entire method should look something like this:

public void jsonWriter(List<Employee> employees, String filePath) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try(FileWriter writer = new FileWriter(filePath)) {
gson.toJson(employees, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Step 4: Now, build your Employee objects, add them to a List and call this method with the appropriate filePath

        Employee arya = new Employee("Stark", "#81, 2nd main, Winterfell", 2, "Arya");
Employee jon = new Employee("Snow", "#81, 2nd main, Winterfell", 1, "Jon");
Employee sansa = new Employee("Stark", "#81, 2nd main, Winterfell", 3, "Sansa");

List<Employee> employees = new ArrayList<>();
employees.add(jon);
employees.add(arya);
employees.add(sansa);

jsonWriter(employees, "C:/downloads/employees.json");

After running this code, the contents of JSON file will look something like this:

[
{
"lastName": "Snow",
"address": "#81, 2nd main, Winterfell",
"id": 1,
"name": "Jon"
},
{
"lastName": "Stark",
"address": "#81, 2nd main, Winterfell",
"id": 2,
"name": "Arya"
},
{
"lastName": "Stark",
"address": "#81, 2nd main, Winterfell",
"id": 3,
"name": "Sansa"
}
]

I hope this will help you in your learning process.

Note: I've used some random Employee names and details. You can replace it with your required details.

How to convert pretty format json file into a simple single line json file using java?

A better and more complete version of this answer with proper error handling and removal of extra spaces.

One problem of the referred answer is that it uses .concat() without .trim() - a very deeply nested pretty-JSON's indents will be visible as extra spaces in final output.

String unprettyJSON = null;

try {
unprettyJSON = Files.readAllLines(Paths.get("pretty.json"))
.stream()
.map(String::trim)
.reduce(String::concat)
.orElseThrow(FileNotFoundException::new);
} catch (IOException e) {
e.printStackTrace();
}

Output with trim:

[{"Employee ID": 1,"Name": "Abhishek","Designation": "Software Engineer"},{"Employee ID": 2,"Name": "Garima","Designation": "Email Marketing Specialist"}][{"Employee ID": 1,"Name": "Abhishek","Designation": "Software Engineer"},{"Employee ID": 2,"Name": "Garima","Designation": "Email Marketing Specialist"}]

Output without trim:

[ {  "Employee ID": 1,  "Name": "Abhishek",  "Designation": "Software Engineer" }, {  "Employee ID": 2,  "Name": "Garima",  "Designation": "Email Marketing Specialist" }][   {      "Employee ID": 1,      "Name": "Abhishek",      "Designation": "Software Engineer"   },   {      "Employee ID": 2,      "Name": "Garima",      "Designation": "Email Marketing Specialist"   }]


Related Topics



Leave a reply



Submit