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

neu242 picture neu242 · May 31, 2011 · Viewed 111.4k times · Source

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.

Answer

Heath Borders picture Heath Borders · Oct 18, 2014
int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);

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