I have a compact JSON string, and I want to format it nicely in Java without having to deserialize it first -- e.g. just like jsonlint.org does it. Are there any libraries out there that provides this?
A similar solution for XML would also be nice.
We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.
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.
int spacesToIndentEachLevel = 2; new JSONObject(jsonString).toString(spacesToIndentEachLevel);
Using org.json.JSONObject
(built in to JavaEE and Android)
Use gson. https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(my_bean);
output
{ "name": "mkyong", "age": 35, "position": "Founder", "salary": 10000, "skills": [ "java", "python", "shell" ] }
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