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.
This question is related to
java
json
formatting
pretty-print
If you are using jackson you can easily achieve this with configuring a SerializationFeature
in your ObjectMapper
:
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValueAsString(<yourObject>);
Thats it.
I fount a very simple solution:
<dependency>
<groupId>com.cedarsoftware</groupId>
<artifactId>json-io</artifactId>
<version>4.5.0</version>
</dependency>
Java code:
import com.cedarsoftware.util.io.JsonWriter;
//...
String jsonString = "json_string_plain_text";
System.out.println(JsonWriter.formatJson(jsonString));
Underscore-java library has methods U.formatJson(json)
and U.formatXml(xml)
. I am the maintainer of the project.
int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);
Using org.json.JSONObject
(built in to JavaEE and Android)
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.
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"
]
}
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.
Source: Stackoverflow.com