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?
Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.
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.
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 .
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With