60

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.

BartoszKP
  • 33,416
  • 13
  • 100
  • 127
neu242
  • 15,777
  • 17
  • 75
  • 111

8 Answers8

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

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

Heath Borders
  • 29,483
  • 16
  • 137
  • 246
  • 2
    What library does this use? As is it is not a very helpful answer. – Andrew Oct 28 '14 at 09:47
  • @Andrew Backer, this is not a library. As Heath Borders said, it is built into the Android libraries. I've tested this and it works perfectly without any libraries. – tambykojak Nov 25 '14 at 08:11
  • 1
    Hm... I'm not developing for Android, and I don't deploy to a java EE container... hence the need for clarification. Thanks for adding that :) So for someone like me, distributing a java app targeting SE, it would be a library such as `org.json:json:20090211`? – Andrew Nov 26 '14 at 09:29
  • for those of us using Android, this is very useful and not really clear in the quick view of the docs. Didn't expect it to be built in. – manroe Jun 05 '15 at 22:40
  • 6
    **`org.json.JSONObject` is not built into JavaEE**. The `JSON-P` library for `JsonObject` is `javax.json.JsonObject`. – Buhake Sindi Jul 11 '16 at 08:07
  • greattttt, this is very useful – dadan Oct 19 '17 at 03:15
  • The dependency with group ID of `org.json` and artifact ID of `json` in the Maven POM file or in your Gradle also supports prettifying JSON data by passing in the indent level in the `toString(int)` method. – tom_mai78101 May 15 '20 at 18:50
  • This is really useful in Spring Boot. – Arjun Sunil Kumar May 22 '20 at 14:23
  • this is very useful. but one problem. if data is large, all data not showing in. Any suggestion – Aminul Haque Aome Jun 10 '21 at 10:37
21

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"
  ]
}
Changhoon
  • 3,316
  • 34
  • 67
12

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.

vcycyv
  • 528
  • 5
  • 8
10

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.

Davoud Taghawi-Nejad
  • 15,097
  • 11
  • 61
  • 81
  • Used this little library, with some modifications to the output format. Thanks for letting me know about it. – Andrew Oct 28 '14 at 10:40
  • Not only was this the first solution to work on my environment, it finally confirmed that I know how to use Gradle to properly pull in thrid-party libraries! A good day, Thanks! – Shadoninja Dec 26 '15 at 21:00
  • I hoped that this tiny library would reformat an existing JSON string without deserializing it first but looking at the source code proved me wrong. This formatJson(..) method internally deserializes the JSON string and then serializes it back to a formatted JSON string. – Sven Döring Oct 08 '19 at 14:20
9

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.

Buhake Sindi
  • 85,564
  • 27
  • 164
  • 223
4

I think for pretty-printing something, it's very helpful to know its structure.

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

Alois Mahdal
  • 10,043
  • 7
  • 49
  • 69
Waldheinz
  • 10,318
  • 3
  • 30
  • 59
2

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));
James Graham
  • 39,063
  • 41
  • 167
  • 242
2

Underscore-java library has methods U.formatJson(json) and U.formatXml(xml).

Valentyn Kolesnikov
  • 1,840
  • 1
  • 21
  • 28