Org.Json - Quick Guide



Org.Json - Overview

org.json or JSON-Java is a simple Java based toolkit for JSON. You can use org.json to encode or decode JSON data.

Features

  • Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627.

  • Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json.

  • XML Conversion − It provides conversion capability from JSON to XML and vice-versa.

  • HTTP Headers − Supports HTTP Header conversion to JSON and vice versa.

  • Cookie − Provides support for Cookie conversion to JSON and vice versa.

  • CDL − Provides support to convert comma separated list to JSON and vice versa.

  • No dependency − No external library dependency. Can be independently included.

  • Java 1.6-21 compatible − Source code and the binary are Java 1.6-21 compatible

Org.Json - Environment Setup

This chapter takes you through the process of setting up Org.Json on Windows and Linux based systems. Org.Json can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation.

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-24, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-24;%PATH% 
set JAVA_HOME=C:\jdk-24

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-24 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-24/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-24

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Install Org.Json Library

Download the latest version of org.json jar file from org.json @ MVNRepository. At the time of writing this tutorial, we have downloaded json-20250517.jar, and copied it into C:\>JSON folder.

OS Archive name
Windows json-20250517.jar
Linux json-20250517.jar
Mac json-20250517.jar

Set JSON_JAVA Environment

Set the JSON_JAVA environment variable to point to the base directory location where org.json jar is stored on your machine. Let's assuming we've stored json-20250517.jar in the JSON folder.

Sr.No OS & Description
1

Windows

Set the environment variable JSON_JAVA to C:\JSON

2

Linux

export JSON_JAVA = /usr/local/JSON

3

Mac

export JSON_JAVA = /Library/JSON

Set CLASSPATH Variable

Set the CLASSPATH environment variable to point to the JSON.simple jar location.

Sr.No OS & Description
1

Windows

Set the environment variable CLASSPATH to %CLASSPATH%;%JSON_JAVA%\json-20250517.jar;.;

2

Linux

export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-20250517.jar:.

3

Mac

export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-20250517.jar:.

Org.Json - CDL Class

CDL class provides static methods to convert a comma delimited text into a JSONArray, and vice versa.

Following methods are covered in the example.

  • rowToJSONArray(String) − Converts a comma delimited text to JSONArray Object.

  • rowToString(JSONArray) − Converts a JSONArray to comma delimited text.

  • toJSONArray(String) − Converts a multi-line comma delimited text to Object of JSONArray objects.

  • toJSONArray(JSONArray, String) − Converts a JSONArray Object and comma delimited text to JSONArray Object.

Example - Conversion of CSV data to JSON Array and Vice Versa

JsonDemo.java

package com.tutorialspoint;

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;

public class JsonDemo {
   public static void main(String[] args) {
      String csvData = "INDIA, UK, USA";

      //Case 1: CSV to JSON Array 
      JSONArray jsonArray = CDL.rowToJSONArray(new JSONTokener(csvData));        
      System.out.println(jsonArray);

      //Case 2: JSONArray to CSV        
      System.out.println(CDL.rowToString(jsonArray));
   }
}

Output

["INDIA","UK","USA"]
INDIA,UK,USA

Example - Conversion of CSV data with headers to JSON Array of Objects

JsonDemo.java

package com.tutorialspoint;

import org.json.CDL;

public class JsonDemo {
   public static void main(String[] args) {
      //Case 3: CSV to JSONArray of Objects
      String csvData = "empId, name, age \n" +
         "1, Mark, 22 \n" +
         "2, Robert, 35 \n" +
         "3, Julia, 18";
      System.out.println(CDL.toJSONArray(csvData));
   }
}

Output

[{"name":"Mark","empId":"1","age":"22"},{"name":"Robert","empId":"2","age":"35"},{"name":"Julia","empId":"3","age":"18"}]

Example - Conversion of JSON Array to CSV without headers

JsonDemo.java

package com.tutorialspoint;

import org.json.CDL;
import org.json.JSONArray;

public class JsonDemo {
   public static void main(String[] args) {
      //Case 4: CSV without header        
      JSONArray jsonArray = new JSONArray();
      jsonArray.put("empId");
      jsonArray.put("name");
      jsonArray.put("age");
      String csvData = "1, Mark, 22 \n" + "2, Robert, 35 \n" + "3, Julia, 18";
      System.out.println(CDL.toJSONArray(jsonArray,csvData));
   }
}

Output

[{"name":"Mark","empId":"1","age":"22"},{"name":"Robert","empId":"2","age":"35"},{"name":"Julia","empId":"3","age":"18"}]

Org.Json - Cookie Class

Cookie class provides static methods to convert web browser's cookie text into a JSONObject, and vice versa.

Following methods are covered in the example.

  • toJSONObject(String) − Converts a cookie text to JSONObject Object.

  • toString(JSONObject) − Converts a JSONObject to cookie text.

Example - Cookie to Json Object Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.Cookie;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2026 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject jsonObject = Cookie.toJSONObject(cookie);
      System.out.println(jsonObject);   
   }
}

Output

{"path":"/","expires":"Thu, 15 Jun 2026 12:00:00 UTC","name":"username","value":"Mark Den"}

Example - Json Object to Cookie Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.Cookie;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2026 12:00:00 UTC; path = /";
      JSONObject jsonObject = Cookie.toJSONObject(cookie);

      //Case 2: Converts JSONObject to Cookie String
      System.out.println(Cookie.toString(jsonObject));        
   }
}

Output

username=Mark Den;path=/;expires=Thu, 15 Jun 2026 12:00:00 UTC

Org.Json - CookieList Class

CookieList class provides static methods to convert Cookie List to JSONObject, and vice versa. Cookie List is a sequence of name/value pairs.

Following methods are covered in the example.

  • toJSONObject(String) − Converts a cookie list text to JSONObject Object.

  • toString(JSONObject) − Converts a JSONObject to cookie list text.

Example - JSON Object to Cookie List Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.Cookie;
import org.json.CookieList;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2020 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject cookieJSONObject = Cookie.toJSONObject(cookie);

      JSONObject cookielistJSONObject = new JSONObject();       
      cookielistJSONObject.put(cookieJSONObject.getString("name"), 
         cookieJSONObject.getString("value"));       

      String cookieList = CookieList.toString(cookielistJSONObject);        
      System.out.println(cookieList);
   }
}

Output

username=Mark Den

Example - Cookie List to Json Object Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.Cookie;
import org.json.CookieList;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2020 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject cookieJSONObject = Cookie.toJSONObject(cookie);

      JSONObject cookielistJSONObject = new JSONObject();       
      cookielistJSONObject.put(cookieJSONObject.getString("name"), 
         cookieJSONObject.getString("value"));       

      String cookieList = CookieList.toString(cookielistJSONObject);        
      System.out.println(CookieList.toJSONObject(cookieList));
   }
}

Output

{"username":"Mark Den"}

Org.Json - HTTP Class

A JSONArray class object is an ordered sequence of values. It provides methods to access values by index and to put values. Following types are supported −

  • Boolean

  • JSONArray

  • JSONObject

  • Number

  • String

  • JSONObject.NULL object

Example - JsonArray of Strings

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONArray list = new JSONArray();

      list.put("Apple");
      list.put("Banana");
      list.put("Orange");
      list.put("Mango");
      list.put("Guava");

      System.out.println("JSONArray: ");
      System.out.println(list);
   }
}

Output

JSONArray: 
["Apple","Banana","Orange","Mango","Guava"]

Example - JsonArray of Integers

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONArray list = new JSONArray();

      list.put(Integer.valueOf(100));
      list.put(Integer.valueOf(200));
      list.put(Integer.valueOf(300));
      list.put(Integer.valueOf(400));
      list.put(Integer.valueOf(500));

      System.out.println("JSONArray: ");
      System.out.println(list);
   }
}

Output

JSONArray: 
[100,200,300,400,500]

Example - JsonArray of Mixed Types

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONArray list = new JSONArray();

      list.put("foo");
      list.put(Integer.valueOf(100));
      list.put(Double.valueOf(1000.21));
      list.put(Boolean.TRUE);
      list.put(JSONObject.NULL);

      System.out.println("JSONArray: ");
      System.out.println(list);
   }
}

Output

JSONArray: 
["foo",100,1000.21,true,null]

Org.Json - JSONML Class

JSONML class provides static methods to convert a XML text into a JSONArray, and vice versa.

Following methods are covered in the example.

  • toJSONArray(String) − Converts a XML to JSONArray Object.

  • toJSONObject(String) − Converts a XML to JSONObject Object.

  • toString(JSONArray) − Gives a XML from a JSONArray Object.

  • toString(JSONObject) − Gives a XML from a JSONObject Object.

Example - JSONArray to XML Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;
import org.json.JSONML;

public class JsonDemo {
   public static void main(String[] args) {
      JSONArray list = new JSONArray();
      list.put("name");
      list.put("Robert");     

      System.out.println("XML from a JSONArray: ");
      String xml = JSONML.toString(list);
      System.out.println(xml);
   }
}

Output

XML from a JSONArray: 
<name>Robert</name>

Example - XML to JSONArray Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;
import org.json.JSONML;

public class JsonDemo {
   public static void main(String[] args) {
      String xml = "<name>Robert</name>";
   
      System.out.println("JSONArray from a XML: ");
      JSONArray list = JSONML.toJSONArray(xml);
      System.out.println(list);
   }
}

Output

JSONArray from a XML: 
["name","Robert"]

Example - JSONObject to XML Conversion and Vice Versa

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;
import org.json.JSONML;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      String xml = "<name>Robert</name>";
      System.out.println("JSONObject from a XML: ");
      JSONObject object = JSONML.toJSONObject(xml);
      System.out.println(object);

      System.out.println("XML from a JSONObject: ");
      xml = JSONML.toString(object);
      System.out.println(xml);
   }
}

Output

JSONObject from a XML: 
{"childNodes":["Robert"],"tagName":"name"}
XML from a JSONObject: 
<name>Robert</name>

Org.Json - JSONObject Class

JSONObject class is a unordered collection of key-value pairs. It provides methods to access values by key and to put values. Following types are supported −

  • Boolean

  • JSONArray

  • JSONObject

  • Number

  • String

  • JSONObject.NULL object

Example - JSONObject of Strings

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONObject week = new JSONObject();
      week.put("Mon", "Monday");
      week.put("Tue", "Tuesday");
      week.put("Wed", "Wednesday");
      week.put("Thu", "Thursday");
      week.put("Fri", "Friday");

      System.out.println(week);
   }
}

Output

{"Thu":"Thursday","Tue":"Tuesday","Wed":"Wednesday","Fri":"Friday","Mon":"Monday"}

Example - JSONObject of Integers

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONObject weeklyScores = new JSONObject();
      weeklyScores.put("Mon", 100);
      weeklyScores.put("Tue", 101);
      weeklyScores.put("Wed", 102);
      weeklyScores.put("Thu", 103);
      weeklyScores.put("Fri", 104);

      System.out.println(weeklyScores);
   }
}

Output

{"Thu":103,"Tue":101,"Wed":102,"Fri":104,"Mon":100}

Example - JSONObject of Mixed Types

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", Double.valueOf(1000.21));
      jsonObject.put("Active", Boolean.TRUE);
      jsonObject.put("Other Details", JSONObject.NULL);

      JSONArray list = new JSONArray();
      list.put("foo");
      list.put(new Integer(100));
      jsonObject.put("list",list);
      System.out.println(jsonObject);
   }
}

Output

{"Active":true,"Other Details":null,"ID":1,"Fees":1000.21,"list":["foo",100],"Name":"Robert"}

Org.Json - JSONStringer Class

JSONStringer is a utility class to build a JSON Text quickly which confirms to JSON Syntax rules. Each instance of JSONStringer can produce one JSON text.

Example - Creating a JSON Object

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONStringer;

public class JsonDemo {
   public static void main(String[] args) { 
      String jsonText = new JSONStringer()
         .object()
         .key("Name")
         .value("Robert")
         .endObject()
         .toString();
      System.out.println(jsonText);
   }
}

Output

{"Name":"Robert"}

Example - Creating a JSON Array

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONStringer;

public class JsonDemo {
   public static void main(String[] args) { 
      String jsonText = new JSONStringer()
         .array()
         .value("Robert")
         .value("Julia")
         .value("Dan")
         .endArray()
         .toString();
      System.out.println(jsonText);
   }
}

Output

["Robert","Julia","Dan"]

Example - Creating a JSON Array with an Object

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONStringer;

public class JsonDemo {
   public static void main(String[] args) { 
      String jsonText = new JSONStringer()
         .array()
         .value("Robert")
         .value("Julia")
         .value("Dan")
         .object()
         .key("Name")
         .value("Robert")
         .endObject()  
         .endArray()
         .toString();
      System.out.println(jsonText);
   }
}

Output

["Robert","Julia","Dan",{"Name":"Robert"}]

Org.Json - Property Class

Property class provides static methods to convert properties text into a JSONObject, and vice versa.

Following methods are covered in the example.

  • toJSONObject(Properties) − Converts a properties data to JSONObject Object.

  • toProperties(JSONObject) − Converts a JSONObject to properties object.

Example - Properties to JSON Object Conversion

JsonDemo.java

package com.tutorialspoint;

import java.util.Properties;
import org.json.JSONObject;
import org.json.Property;

public class JsonDemo {
   public static void main(String[] args) {
      Properties properties = new Properties();
      properties.put("title", "This is a title text");
      properties.put("subtitle", "This is a subtitle text");

      System.out.println("Properties to JSON");
      JSONObject jsonObject = Property.toJSONObject(properties);
      System.out.println(jsonObject);

      System.out.println("JSON to properties");
      System.out.println(Property.toProperties(jsonObject));
   }
}

Output

Properties to JSON
{"subtitle":"This is a subtitle text","title":"This is a title text"}

Example - JSON Object to Properties Conversion

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONObject;
import org.json.Property;

public class JsonDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("title", "This is a title text");
      jsonObject.put("subtitle", "This is a subtitle text");

      System.out.println("JSON to properties");
      System.out.println(Property.toProperties(jsonObject));
   }
}

Output

JSON to properties
{subtitle=This is a subtitle text, title=This is a title text}

Org.Json - XML Class

XML class provides static methods to convert a XML text into a JSONObject, and vice versa.

Following methods are covered in the example.

  • toJSONObject(String) − Converts a XML to JSONArray Object.

  • toString(JSONObject) − Gives a XML from a JSONObject Object.

Example - Converting XML to JSON Object

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONObject;
import org.json.XML;

public class JsonDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", Double.valueOf(1000.21));
      jsonObject.put("Active", Boolean.TRUE);
      jsonObject.put("Details", JSONObject.NULL);

      //Convert a JSONObject to XML
      String xmlText = XML.toString(jsonObject);
      System.out.println(xmlText);
   }
}

Output

<Active>true</Active><Details>null</Details><ID>1</ID><Fees>1000.21</Fees><Name>Robert</Name>

Example - Converting JSON Object to XML

JsonDemo.java

package com.tutorialspoint;

import org.json.XML;

public class JsonDemo {
   public static void main(String[] args) { 
      //Convert a JSONObject to XML
      String xmlText = "<Active>true</Active><Details>null</Details>"
         +"<ID>1</ID><Fees>1000.21</Fees><Name>Robert</Name>";
      //Convert an XML to JSONObject
      System.out.println(XML.toJSONObject(xmlText));
   }
}

Output

{"Active":true,"Details":null,"ID":1,"Fees":1000.21,"Name":"Robert"}

Org.Json - JSONException Handling

Utility classes of org.json throws JSONException in case of invalid JSON. Following example shows how to handle JSONException.

Example - Handling JSONException

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONException;
import org.json.XML;

public class JsonDemo {
   public static void main(String[] args) {
      try {
         //XML tag name should not have space.
         String xmlText = "<Other Details>null</Other Details>";
         System.out.println(xmlText);

         //Convert an XML to JSONObject
         System.out.println(XML.toJSONObject(xmlText));
      } 
      catch(JSONException e){   
         System.out.println(e.getMessage());
      }
   }
}

Output

<Other Details>null</Other Details>
Misshaped close tag at 34 [character 35 line 1]

Example - Throwing JSONException

JSONException is a Runtime Exception and is not required to be declared as throws statement. But we can throw it to make code clearer and cleaner.

JsonDemo.java

package com.tutorialspoint;

import org.json.JSONException;
import org.json.XML;

public class JsonDemo {
   public static void main(String[] args) throws JSONException {
         //XML tag name should not have space.
         String xmlText = "<Other Details>null</Other Details>";
         System.out.println(xmlText);

         //Convert an XML to JSONObject
         System.out.println(XML.toJSONObject(xmlText));
   }
}

Output

<Other Details>null</Other Details>
Exception in thread "main" org.json.JSONException: Misshaped close tag at 34 [character 35 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:568)
    at org.json.XML.parse(XML.java:321)
    at org.json.XML.parse(XML.java:443)
    at org.json.XML.toJSONObject(XML.java:777)
    at org.json.XML.toJSONObject(XML.java:863)
    at org.json.XML.toJSONObject(XML.java:662)
    at com.tutorialspoint.JsonDemo.main(JsonDemo.java:13)
Advertisements