Pretty print JSON using org.json library in Java?

JavaJSONObject Oriented ProgrammingProgramming

The JSON is a lightweight, text-based and language-independendata exchange format. A.JSONObject can parse text from a string to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. The files in the org.json package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON, XML, HTTP  headers, Cookies, and CDL.

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

Example

import org.json.*;
public class JSONPrettyPrintTest {
   public static void main(String args[]) throws JSONException {
      String json = "{" +
                    "Name : Jai," +
                    "Age : 25, " +
                    "Salary: 25000.00 " +
                    "}";
      JSONObject jsonObj = new JSONObject(json);
      System.out.println("Pretty Print of JSON:");
      System.out.println(jsonObj.toString(4)); // pretty print json
   }
}

Output

Pretty Print of JSON:
{
   "Salary": 25000,
   "Age": 25,
   "Name": "Jai"
}
raja
Published on 26-Sep-2019 06:29:13
Advertisements