Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 472
neu242 Avatar asked May 31 '11 09:05

neu242


People also ask

How do I print a pretty JSON file?

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.

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.


2 Answers

int spacesToIndentEachLevel = 2; new JSONObject(jsonString).toString(spacesToIndentEachLevel); 

Using org.json.JSONObject (built in to JavaEE and Android)

like image 196
Heath Borders Avatar answered Sep 29 '22 07:09

Heath Borders


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"   ] } 
like image 24
Changhoon Avatar answered Sep 29 '22 08:09

Changhoon