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.
Solution 1:
int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);
Using org.json.JSONObject
(built in to JavaEE and Android)
Solution 2:
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"
]
}
Solution 3:
Another way to use gson:
String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));
It can be used when you don't have the bean as in susemi99's post.
Solution 4:
In one line:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
or
System.out.println(JsonWriter.formatJson(jsonString.toString()));
The json-io libray (https://github.com/jdereg/json-io) is a small (75K) library with no other dependencies than the JDK.
In addition to pretty-printing JSON, you can serialize Java objects (entire Java object graphs with cycles) to JSON, as well as read them in.