Introduction to org.json
JSON is short for JavaScript Object Notation and is a widely-used file format for storing and transmitting data. It uses a human-readable format and stores data in key-value pairs or as arrays. In this tutorial, we will learn how to work with JSON in Java with the help of the org.json library.
org.json Library
The org.json library provides us a lot of classes to work with JSON. It is also known as the Java-JSON library. We can use the JSONObject
class to create JSON objects. We can also create JSON arrays by using the JSONArray class. It also provides convenient classes and methods for the conversion of JSON to other formats.
JSONObject in org.json
- A JSONObject is used to store key-value pairs. The key can only be a non-null string, but values can be of any type.
- The put() method is used to add a key-value pair to the JSONObject.
- We can fetch the value corresponding to a key by using the get(String key) method.
- We can also use the opt(String key) method to fetch the object associated with the key.
- There are a lot of methods available for this class, but these are used most frequently.
The code below shows the working of these methods.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("one", 1);
jsonObj.put("two", "2");
jsonObj.put("three", false);
jsonObj.put("four", JSONObject.NULL);
System.out.println("The JSONObject is: " + jsonObj);
System.out.println("get(one): " + jsonObj.get("one"));
System.out.println("get(two): " + jsonObj.get("two"));
System.out.println("get(three): " + jsonObj.get("three"));
System.out.println("get(four): " + jsonObj.get("four"));
}
}
The JSONObject is: {"four":null,"one":1,"two":"2","three":false}
get(one): 1
get(two): 2
get(three): false
get(four): null
Creating JSONObject Using a Map
The JSONObject constructor can take a map instance, and it will initialize the JSONObject with the key-value pairs present in the map.
import java.util.HashMap;
import java.util.Map;
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
map.put("four", 4);
JSONObject jsonObj = new JSONObject(map);
System.out.print(jsonObj);
}
}
{"four":4,"one":1,"two":2,"three":3}
Creating JSONObject Using a String
If we have a valid JSON string, then we can use this string to initialize a JSONObject. The JSONObject constructor can initialize the JSONObject with the key-value pairs obtained from the JSON string.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String jsonStr = "{\"one\":\"1\",\"two\":\"2\",\"three\":\"3\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
System.out.print(jsonObj);
}
}
{"one":"1","two":"2","three":"3"}
Creating JSONObject Using a Bean Class
We can pass a Java Bean class object to the JSONObject constructor, and it will create a JSON object with the class attributes and the values set in the bean object.
Let's use the following Java Bean class for this purpose.
import java.io.Serializable;
public class Student implements Serializable
{
private String name;
private Double gpa;
Student(){}
Student(String s, Double d)
{
this.name = s;
this.gpa = d;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getGpa() {
return gpa;
}
public void setGpa(Double gpa) {
this.gpa = gpa;
}
}
Now, when we create a JSONObject using an instance of this class, then we will have the name and GPA as the keys.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
Student student = new Student();
student.setName("Justin");
student.setGpa(8.50);
JSONObject jsonObj = new JSONObject(student);
System.out.print(jsonObj);
}
}
{"name":"Justin","gpa":8.5}
JSONArray in org.json
- A JSONArray is an ordered collection of values.
- The put() method is used to add values to the array. The values can be of any type.
- We can fetch these values by their index using the get() method.
- A JSONArray is represented as a string that starts and ends with square brackets and contains comma-separated values.
Let's create a JSONArray by using the methods discussed above.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("one", 1);
jsonObj.put("two", "2");
JSONArray jsonArr = new JSONArray();
//Adding values to the JSONArray
jsonArr.put("String");
jsonArr.put(100.0);
jsonArr.put(JSONObject.NULL);
jsonArr.put(jsonObj);
System.out.println(jsonArr);
System.out.println("Element at index 1:" + jsonArr.get(1));
System.out.println("Element at index 3:" + jsonArr.get(3));
}
}
["String",100,null,{"one":1,"two":"2"}]
Element at index 1:100.0
Element at index 3:{"one":1,"two":"2"}
Creating JSONArray Using a string
The JSONArray constructor can take a JSON string to initialize the array. Make sure that the string passed to the constructor is a valid JSON string.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String jsonStr = "[1, \"String\", false]";
JSONArray jsonArr = new JSONArray(jsonStr);
System.out.print(jsonArr);
}
}
[1,"String",false]
Creating JSONArray Using Collections
We can also use collections to initialize a JSONArray. The JSONArray constructor is used to do this.
import java.util.ArrayList;
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
ArrayList<String> arrList = new ArrayList<>();
arrList.add("one");
arrList.add("2");
arrList.add("three");
JSONArray jsonArr = new JSONArray(arrList);
System.out.print(jsonArr);
}
}
["one","2","three"]
JSONTokener in org.json
The JSONTokener class is used to split a string into individual characters. This class is not frequently used. We have other popular Java methods that can achieve the same result. This class is used by other classes(JSONObject and JSONArray) to parse JSON strings.
Let's try to split a string using this class. We will use the more() method to check if the JSONTokener contains more characters. We will use the next() method to fetch individual characters.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONTokener jsonTokener = new JSONTokener("This is a string.");
while(jsonTokener.more())
System.out.println(jsonTokener.next());
}
}
T
h
i
s
i
s
a
s
t
r
i
n
g
.
Comma Delimited List in org.json
The comma-delimited list(CDL) class of the org.json library provides easy conversion methods between JSONObject or JSONArray and a comma-delimited text. We will also need the JSONTokener for some of the conversions.
JSONArray from Comma Delimited Text
We can convert a comma-delimited string to a JSONArray by first using the JSONTokener, and then using the rowToJSONArray() method of the CDL class.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String s = "This, is, a, string, .";
JSONTokener jsonTokener = new JSONTokener(s);
JSONArray jsonArrUsingCDL = CDL.rowToJSONArray(jsonTokener);
System.out.print(jsonArrUsingCDL);
}
}
["This","is","a","string","."]
Comma Delimited Text From JSONArray
To convert our JSONArray to a comma-delimited string, we can use the rowToString() method of the CDL class.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String s1 = "This, is, a, string, .";
JSONTokener jsonTokener = new JSONTokener(s1);
//String to JSONArray
JSONArray jsonArrUsingCDL = CDL.rowToJSONArray(jsonTokener);
System.out.println("JSON Array: " + jsonArrUsingCDL);
//JSONArray to String
String s2 = CDL.rowToString(jsonArrUsingCDL);
System.out.print("String from JSON Array: " + s2);
}
}
JSON Array: ["This","is","a","string","."]
String from JSON Array: This,is,a,string,.
JSONArray of JSONObjects from Comma Delimited Text
We can format a string into headers(or keys) and JSONObject values to create an array of JSONObjects. We will use the toJSONArray() method of the CDL class.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String jsonObjs = "name, gpa, regNo \n" //Headers
+ "Justin, 8.21, 101 \n"//First JSONObject
+ "Jessica, 8.55, 102 \n"; //Second JSONObject
JSONArray jsonArr = CDL.toJSONArray(jsonObjs);
System.out.println("First JSONObject in the JSONArray: " + jsonArr.get(0));
System.out.println("First JSONObject in the JSONArray: " + jsonArr.get(1));
}
}
First JSONObject in the JSONArray: {"regNo":"101","name":"Justin","gpa":"8.21"}
First JSONObject in the JSONArray: {"regNo":"102","name":"Jessica","gpa":"8.55"}
The toJSONArray() has an overloaded method that can take another JSONArray() as a parameter. This JSONArray will contain the headers(or keys) for the JSONObjects. We will also require a string that will contain the JSONObject values.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONArray header = new JSONArray();
header.put("Name");
header.put("GPA");
header.put("RegNo");
String jsonObjs = "Justin, 8.21, 101 \n"//First JSONObject
+ "Jessica, 8.55, 102 \n"; //Second JSONObject
JSONArray jsonArr = CDL.toJSONArray(header, jsonObjs);
System.out.println("First JSONObject in the JSONArray: " + jsonArr.get(0));
System.out.println("First JSONObject in the JSONArray: " + jsonArr.get(1));
}
}
First JSONObject in the JSONArray: {"RegNo":"101","GPA":"8.21","Name":"Justin"}
First JSONObject in the JSONArray: {"RegNo":"102","GPA":"8.55","Name":"Jessica"}
Cookie Class of org.json
The org.json library contains a Cookie class that can convert web browser cookies to JSONObjects and JSONObjects back to cookies.
JSONObject from Cookie String
We will use the toJSONObject() of this class to perform the conversion. Make sure that the string representing the cookies is in the correct format.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String cookie = "username = Justin Kan; expires = Thu, 5 Jul 2021 12:00:00 UTC; path = /\"";
JSONObject jsonObjCookie = Cookie.toJSONObject(cookie);
System.out.println(jsonObjCookie);
}
}
{"path":"/\"","expires":"Thu, 5 Jul 2021 12:00:00 UTC","name":"username","value":"Justin Kan"}
Cookie String from JSONObject
The toString() method of this class can convert a JSONObject containing a cookie to a string.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
//String cookie to JSONObject
String cookie = "username = Justin Kan; expires = Thu, 5 Jul 2021 12:00:00 UTC; path = /\"";
JSONObject jsonObjCookie = Cookie.toJSONObject(cookie);
//JSONObject to String cookie
String cookieFromJsonObj = Cookie.toString(jsonObjCookie);
System.out.print(cookieFromJsonObj);
}
}
username=Justin Kan;expires=Thu, 5 Jul 2021 12:00:00 UTC;path=/"
HTTP Class of org.json
The HTTP class of the org.json library is used for conversion between HTTP headers and JSONObjects.
JSONObject from HTTP Header String
Just like the Cookie class, the HTTP class also contains a toJSONObject() method. This is used to convert an HTTP header string to a JSONObject.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String httpString = "POST \"http://www.somesite.com/\" HTTP/1.1";
JSONObject httpJsonObj = HTTP.toJSONObject(httpString);
System.out.print("HTTP JSON Object: " + httpJsonObj);
}
}
HTTP JSON Object: {"Request-URI":"http://www.somesite.com/","Method":"POST","HTTP-Version":"HTTP/1.1"}
HTTP Header String from JSONObject
The HTTP class also contains the toString() method that can convert a JSONObject containing an HTTP header to a string.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONObject httpJsonObj = new JSONObject();
httpJsonObj.put("Method", "POST");
httpJsonObj.put("Request-URI", "http://www.somesite.com/");
httpJsonObj.put("HTTP-Version", "HTTP/1.1");
System.out.println("HTTP JSON Object: " + httpJsonObj);
String stringFromHttpJsonObj = HTTP.toString(httpJsonObj);
System.out.println("String from HTTP JSON Object: " + stringFromHttpJsonObj);
}
}
HTTP JSON Object: {"Request-URI":"http://www.somesite.com/","Method":"POST","HTTP-Version":"HTTP/1.1"}
String from HTTP JSON Object: POST "http://www.somesite.com/" HTTP/1.1
JSONException
When working with the org.json library, we will frequently encounter the JSONException. This exception also contains a message that describes the reason behind the error. Let's take a look at few scenarios where this error is thrown.
JSONException when we use invalid keys
This error will be returned if we try to fetch a JSONObject value using the get() method, but the key does not exist.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONObject jsonObj = new JSONObject();
jsonObj.put("one", 1);
jsonObj.put("two", "2");
jsonObj.put("three", false);
jsonObj.put("four", JSONObject.NULL);
System.out.println(jsonObj.get("five"));//Invalid Key
}
}
Exception in thread "main" org.json.JSONException: JSONObject["five"] not found.
at org.json.JSONObject.get(JSONObject.java:516)
at Demo.main(Demo.java:13)
JSONException when we use invalid JSON Strings
We learned a few different ways where we are using JSON strings for different purposes. However, if the string is not of valid JSON format, then we will get the JSONException.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
String jsonStr = "one : 1, two: 2, three: 3";
JSONObject jsonObj = new JSONObject(jsonStr);
System.out.print(jsonObj);
}
}
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:420)
at Demo.main(Demo.java:9)
JSONException when we use invalid JSONArray Index
Normally, we will get an ArrayIndexOutOfBounds exception if we try to use an invalid index. For JSONArrays, we will get the JSONException.
import org.json.*;
public class Demo
{
public static void main(String[] args) throws JSONException
{
JSONArray jsonArr = new JSONArray();
//Adding values to the JSONArray
jsonArr.put("String");
jsonArr.put(100.0);
jsonArr.put(JSONObject.NULL);
System.out.println("Element at index 10:" + jsonArr.get(10));//Invalid Index
}
}
Exception in thread "main" org.json.JSONException: JSONArray[10] not found.
at org.json.JSONArray.get(JSONArray.java:247)
at Demo.main(Demo.java:13)
Summary
The json.org is a popular Java package used for working with JSON. In this tutorial, we looked at some of the most important classes and methods of this package. We also learned about the JSONException, which is used by all classes of this package.