Introduction
JSON (JavaScript Object Notation) is widely used for data interchange due to its simplicity and human-readable structure. However, when it comes to working with JSON in applications, it’s often presented in a compact, unformatted way, which makes it difficult to read and understand. To make it more readable, we need to format the JSON string with proper indentation, line breaks, and spacing.
In this example, we will write a Java program that takes an unformatted JSON string as input and outputs a more readable, well-formatted JSON string. This process involves adding appropriate spaces and new lines to structure the JSON data effectively.
Objective
The objective of this program is to demonstrate how to format a JSON string in Java, making it easier to read and understand. The program will:
- Take an unformatted JSON string as input.
- Format the JSON string with proper indentation and line breaks.
- Output the formatted JSON string for better readability.
Code
import org.json.JSONObject; public class JsonFormatter { public static void main(String[] args) { // Sample unformatted JSON string String jsonString = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"}}"; // Create a JSONObject from the string JSONObject jsonObject = new JSONObject(jsonString); // Convert the JSONObject to a formatted JSON string String formattedJson = jsonObject.toString(4); // 4 is the number of spaces for indentation // Output the formatted JSON string System.out.println("Formatted JSON Output:"); System.out.println(formattedJson); } }
Program Explanation
The program works as follows:
- The
jsonString
variable holds an unformatted JSON string as input. This string is passed into aJSONObject
instance, which is a class from the org.json library designed to handle JSON data. - The method
toString(4)
is called on theJSONObject
instance, where4
is the number of spaces used for indentation. This creates a properly formatted JSON string with line breaks and indentation for readability. - The formatted JSON string is then printed to the console for the user to view.
How to Run the Program
To run this program, follow these steps:
- Ensure that you have the
org.json
library added to your project. You can add it via Maven, Gradle, or download the JAR directly from a reliable source. - Copy the program code into a file named
JsonFormatter.java
. - Compile the program using the Java compiler:
javac JsonFormatter.java
- Run the compiled program:
java JsonFormatter
- The output will display the JSON string formatted with proper indentation and line breaks.