Java – How to pretty-print JSON using JSONObject ?

In this article, we will discuss how to pretty print JSON using JSONObject

1. Required libraries :

1.1 Maven Co-ordinates :

<dependency>
			<groupId>org.json</groupId>
		    <artifactId>json</artifactId>
		    <version>20220924</version>
</dependency>

1.2 JAR files to download :

Download below jar files and include them in Project classpath

1.3 Project class-path :

2. Pretty print JSON :

In the below illustration, we will print JSON in a structured format using JSONObject,

  • 1st step is to read the contents of the JSON String
  • 2nd step is to instantiate JSONObject by passing JSON String as constructorargument
  • 3rd step is to invoke toString() method on the newly created JSONObject passing integer value like 4 which represents indentation or space between start of the line and actual values

JSON file contents – Person.json :

{
  "title" : "Mr.",
  "firstName" : "Sam",
  "lastName" : "Anton",
  "address" : {
    "flatNumber" : "BV-1025",
    "buildingName" : "Shivaji",
    "plotNumber" : "1093",
    "sector" : "Sector 19",
    "city" : "Bengaluru",
    "state" : "Karnataka",
    "country" : "India",
    "nodeName" : "South Bengaluru"
  },
  "items" : [ {
    "itemName" : "Television",
    "itemBoughtYear" : "2014"
  }, {
    "itemName" : "Washing Machine",
    "itemBoughtYear" : "2020"
  }, {
    "itemName" : "Refrigerator",
    "itemBoughtYear" : "2011"
  }, {
    "itemName" : "Grinder",
    "itemBoughtYear" : "2012"
  }, {
    "itemName" : "Computer",
    "itemBoughtYear" : "2010"
  } ]
}

PrettyPrintJSON.java

package in.bench.resources.yaml.conversion;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.json.JSONObject;

public class PrettyPrintJSON {

	public static void main(String[] args) {

		try {
			// read JSON String
			String jsonContent = new String(Files.readAllBytes(Paths.get(
					"C:\\Users\\Demo\\eclipse-workspace\\YamlConversion\\Person.json")));


			// instantiate JSONObject and assign it to String after conversion
			String jsonObject = (new JSONObject(jsonContent)).toString(4);


			// print to console
			System.out.println("Formatted JSON String :- \n" + jsonObject);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output in console :

Formatted JSON String :- 
{
    "firstName": "Sam",
    "lastName": "Anton",
    "address": {
        "nodeName": "South Bengaluru",
        "buildingName": "Shivaji",
        "country": "India",
        "city": "Bengaluru",
        "flatNumber": "BV-1025",
        "plotNumber": "1093",
        "state": "Karnataka",
        "sector": "Sector 19"
    },
    "title": "Mr.",
    "items": [
        {
            "itemName": "Television",
            "itemBoughtYear": "2014"
        },
        {
            "itemName": "Washing Machine",
            "itemBoughtYear": "2020"
        },
        {
            "itemName": "Refrigerator",
            "itemBoughtYear": "2011"
        },
        {
            "itemName": "Grinder",
            "itemBoughtYear": "2012"
        },
        {
            "itemName": "Computer",
            "itemBoughtYear": "2010"
        }
    ]
}

In the following article, we will discuss same example using Jackson or ObjectMapper in detail

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java – How to pretty-print JSON using ObjectMapper ?
Java – How to convert XML to JSON using ObjectMapper ?