Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON String tidy/formatter for Java [closed]

I have a valid JSON String that I want to tidy/format such that each property/value pair is on its own line, etc. (it currently is on one line with no spaces/line breaks).

I am using the Apache Sling JSONObject to model my JSON Object and turn it into a String, so if the Sling JSONObject can be set to output a tidy string (which I do not think it can) that would work too.

If I need a 3rd party lib I would prefer one with as few dependencies as possibles (such as Jackson which only requires the std JDK libs).

like image 479
empire29 Avatar asked Dec 21 '11 20:12

empire29


People also ask

How do I print a JSON string in pretty format?

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.

How do I remove all escape characters from a JSON string in Java?

String jsonFormattedString = jsonStr. replaceAll("\\", "");


1 Answers

With gson you can do:

JsonParser parser = new JsonParser(); Gson gson = new GsonBuilder().setPrettyPrinting().create();  JsonElement el = parser.parse(jsonString); jsonString = gson.toJson(el); // done 
like image 192
Ali Shakiba Avatar answered Sep 19 '22 19:09

Ali Shakiba