Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty-Print JSON in Java

I'm using json-simple and I need to pretty-print JSON data (make it more human readable).

I haven't been able to find this functionality within that library. How is this commonly achieved?

like image 512
mabuzer Avatar asked Nov 05 '10 12:11

mabuzer


People also ask

How do I pretty-print a JSON object?

Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.

How do you print your response in JSON format in Java?

We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.

What is JSON pretty format?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .


1 Answers

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' 
like image 87
Ray Hulha Avatar answered Sep 21 '22 22:09

Ray Hulha