Pretty-Print JSON in Java

java format json string
gson pretty print json string
pretty print java
print json object java
java pretty print object
print json request java
objectmapper pretty print
google json pretty print

I'm using json-simple and I need to pretty-print JSON data (make it more human readable).

I haven't been able to find this functionality within that library. How is this commonly achieved?

GSON can do this in a nice way:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);

Jackson - How to enable pretty print JSON output, Jackson - How to enable pretty print JSON output. In Jackson, we can use writerWithDefaultPrettyPrinter() to pretty print the JSON output. Tested with Founder of Mkyong.com, love Java and open source stuff. Follow him  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. Syntax public java.lang.String toString(int indentFactor) throws JSONException

I used org.json built-in methods to pretty-print the data.

JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation

The order of fields in JSON is random per definition. A specific order is subject to parser implementation.

Pretty print JSON using org.json library 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. These JSON structures can be represented as object models using JsonObject and JsonArray interfaces. We can use the JsonGenerator interface to write the JSON data to an output in a streaming way. The JsonGenerator.PRETTY_PRINTING is a configuration property to generate JSON prettily.

It seems like GSON supports this, although I don't know if you want to switch from the library you are using.

From the user guide:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

How to pretty print JSON using the Gson library in Java?, By using Gson, we can generate JSON and convert JSON to java objects. By default, Gson can print the JSON in compact format. To enable Gson  In Jackson, we can use writerWithDefaultPrettyPrinter() to pretty print the JSON output. Tested with Jackson 2.9.8. 1. Pretty Print JSON. 1.1 By default, Jackson print in compact format: ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); String json = mapper.writeValueAsString(staff); System.out.println(json); Output

With Jackson (com.fasterxml.jackson.databind):

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject))

From: How to enable pretty print JSON output (Jackson)

I know this is already in the answers, but I want to write it separately here because chances are, you already have Jackson as a dependency and so all you will need would be an extra line of code

Convert JSON string to Pretty Print (Java, Gson) (Example), writeValueAsString(Object) . This will produce a pretty formatted JSON. ObjectMapper mapper = new ObjectMapper(); Object jsonObject =  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.

If you are using a Java API for JSON Processing (JSR-353) implementation then you can specify the JsonGenerator.PRETTY_PRINTING property when you create a JsonGeneratorFactory.

The following example has been originally published on my blog post.

import java.util.*;
import javax.json.Json;
import javax.json.stream.*;

Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties);
JsonGenerator jg = jgf.createGenerator(System.out);

jg.writeStartObject()                    // {
    .write("name", "Jane Doe")           //    "name":"Jane Doe",
    .writeStartObject("address")         //    "address":{
        .write("type", 1)                //        "type":1,
        .write("street", "1 A Street")   //        "street":"1 A Street",
        .writeNull("city")               //        "city":null,
        .write("verified", false)        //        "verified":false
    .writeEnd()                          //    },
    .writeStartArray("phone-numbers")    //    "phone-numbers":[
        .writeStartObject()              //        {
            .write("number", "555-1111") //            "number":"555-1111",
            .write("extension", "123")   //            "extension":"123"
        .writeEnd()                      //        },
        .writeStartObject()              //        {
            .write("number", "555-2222") //            "number":"555-2222",
            .writeNull("extension")      //            "extension":null
        .writeEnd()                      //        }
    .writeEnd()                          //    ]
.writeEnd()                              // }
.close();

How to pretty print JSON string using Jackson?, Java program to serialize an Employee object and pretty print the JSON output. public class Employee. {. private  Streaming example Example to use JsonWriter() and JsonReader to stream read and write JSON data.Pretty print JSON output in Gson Pretty print JSON output via GsonBuilder.JSON.simpleSimple Java library for JSON, to read and write […]

Gson - Pretty Print JSON, The Pretty print JSON in Java tutorial shows you how to use Jackson library to pretty print JSON Object and String in the console. JSON Pretty Print helps Pretty JSON data and Print JSON data. It's very simple and easy way to prettify JSON and pretty print JSON. This is the # 1 tool to JSON Prettify. Know more about JSON. What is JSON? JSON Example with all data types including JSON Array. Python Pretty Print JSON; Read JSON File Using Python; Validate JSON using PHP

Pretty print JSON in Java, ) is the application of any of various stylistic formatting conventions to text files, such as source code, markup, and similar kinds of content. With the streaming API, you can use JsonGenerator.copyCurrentEvent () to easily re-output the token stream with whatever pretty-printing applied you want, including the default of no whitespace; this avoids buffering the entire document in memory and building a tree for the document.

Prettyprint, How do you pass a JSON object into a string in Java? Pretty print JSON in Java (Jackson) January 17, 2017 September 9, 2016 by javabycode.com The Pretty print JSON in Java tutorial shows you how to use Jackson pretty print for JSON Object and String in the console.

Comments
  • Well I included code to parse a string into a JsonElement, usually you already have that from previous work you do with the JSON data. But I wanted to include it here to make the usage clearer.
  • Since this answer helped me. I have added code below to shrink this statement to fewer lines if this is what you are looking for. public String prettifyJson(String json) { JsonElement jsonElement = new JsonParser().parse(json); return new GsonBuilder().setPrettyPrinting().create().toJson(jsonElement); }
  • It is possible to answer the OP's question without needing additional libraries, as you can simply access the JSON parser embedded in Rhino (JDK 1.7 and up). I don't think it is desirable to add a library to a project just to format some debugging output. scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
  • In contrast to the org.json alternative, the GSON way of pretty printing keeps the order of the elements intact after transformation.
  • Thanks for the pointer to GsonBuilder, since I was using gson.toJson(object) I simply had to change my instantiation from Gson gson = new Gson(); to Gson gson = new GsonBuilder().setPrettyPrinting().create(); and my code continued to work but pretty printed the object instead of a single line.
  • I also prefer this solution, because you don't need to import additional dependencies like other answers suggest.
  • Missing a crucial import - import org.json.JSONObject;
  • is there anyway to NOT have the fields in random order, I want it in the order I added them?
  • @ThomasAdrian it is not possible with org.json.JSONObject.
  • Underscore-java keeps attribute order while formatting json.
  • The problem with GSON, it's complicated, json-simple is far easier.