How to Read/Write Json in Java?

JSON-Java offers classes like JSONObject and JSONArray that offer various ways to create Json via overloaded constructors. They can be used to read Json as well.

Table of Contents

Json is a human readable, light-weight and language independent data interchange format which is often used in client/server applications via REST Apis. Due to its language independent nature, it can be used with variety of programming languages.

There are various open-source libraries available which are used to read and write Json in java. This article covers one of them called JSON-Java.

JSON-Java

This library offers simple and easy to use classes to read/write and manipulate Json. Following are the maven coordinates of this library. You can put this in your pom.xml in dependencies section to get started with it.

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

The library has these 2 prominent classes that offer various ways to create Json via their overloaded constructors.

JSONObject– A JSONObject is an unordered collection of name/value pairs.

JSONArray– A JSONArray is an ordered sequence of values.

Writing a Json object using JSONObject

JSONObject is used to create a Json object. It offers various constructors that can be used to create Json.

Using Default Constructor

The default constructor internally uses Map implementation hence you can directly add key/value pairs using its put() method.

package com.example.boot;

import org.json.JSONObject;

public class JsonFile {
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("country", "UK");
        jsonObject.put("state", "Birmingham");
        jsonObject.put("street", 23);
        jsonObject.put("capital", false);

        //without indentation
        System.out.println(jsonObject.toString());

        //with indentation
        System.out.println(jsonObject.toString(4));
    }
}

Output

{"country":"UK","capital":false,"street":23,"state":"Birmingham"}
{
    "country": "UK",
    "capital": false,
    "street": 23,
    "state": "Birmingham"
}

Using Map Object

You can create Json from a map object also. Populate the map object and pass it to the constructor.

package com.example.boot;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class JsonFile {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("country", "UK");
        map.put("state", "Birmingham");
        map.put("street", 23);
        map.put("capital", false);
        JSONObject jsonObject = new JSONObject(map); // via map object
        System.out.println(jsonObject.toString(4));
    }
}

Output

{
    "country": "UK",
    "capital": false,
    "state": "Birmingham",
    "street": 23
}

If any custom object/bean is put in the map, then the bean is converted to Json via its getter methods. See below.

Using Java Bean

You can create Json via Java bean also. In this case, its getter methods are called to create Json keys and values.

package com.example.boot;

import org.json.JSONObject;

public class JsonFile {
    public static void main(String[] args) {
        Location location = new Location("UK", "Birmingham", 23, false);
        JSONObject jsonObject = new JSONObject(location);
        System.out.println(jsonObject.toString(4));
    }

    public static class Location {
        private final String country;
        private final String state;
        private final int street;
        private final boolean capital;

        public Location(String country, String state, int street, boolean capital) {
            this.country = country;
            this.state = state;
            this.street = street;
            this.capital = capital;
        }

        public String getCountry() {
            return country;
        }

        public String getState() {
            return state;
        }

        public int getStreet() {
            return street;
        }

        public boolean isCapital() {
            return capital;
        }
    }
}

Output

{
    "country": "UK",
    "capital": false,
    "street": 23,
    "state": "Birmingham"
}

Writing a Json array using JSONArray

JSONArray also offers various constructors to create Json array. It internally uses ArrayList to store values and renders them in square brackets separated by commas.

Below are the ways to create a Json array.

Using default constructor

The default constructor uses ArrayList internally to store values. Values can be anything like a number, string, Boolean, another Json array, Json object or even null.

You can use get(int index) and put(Object value) methods to operate the Json array.

package com.example.boot;

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

public class JsonArray {
    public static void main(String[] args) {
        JSONArray array = new JSONArray();
        array.put(10);
        array.put(false);
        array.put("Arizona");

        JSONObject object = new JSONObject();
        object.put("key_one", "value_one");

        array.put(object);
        System.out.println(array.toString(2));
    }
}

Output

[
  10,
  false,
  "Arizona",
  {"key_one": "value_one"}
]

Using collection

A collection object can also be supplied to its constructor to build a Json array.

Let us see an example where a set is used to create a Json object.

package com.example.boot;

import org.json.JSONArray;

import java.util.HashSet;
import java.util.Set;

public class JsonArray {
    public static void main(String[] args) {
        Set<String> names = new HashSet<>(2);
        names.add("Michael");
        names.add("Jordan");
        JSONArray array = new JSONArray(names);
        System.out.println(array);
    }
}

Output

["Jordan","Michael"]

Reading a Json Object from plain String

A plain JSON string can be supplied via constructor to create a json object from it. This string must be a valid JSON string otherwise parsing would fail and you will get an exception.

package com.example.boot;

import org.json.JSONObject;

public class JsonFile {
    public static void main(String[] args) {
        String s = "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A meta-markup language, used to create markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";

        JSONObject jsonObject = new JSONObject(s);
        System.out.println(jsonObject.toString(2));
    }
}

Output

{"glossary": {
  "title": "example glossary",
  "GlossDiv": {
    "GlossList": {"GlossEntry": {
      "GlossTerm": "Standard Generalized Markup Language",
      "GlossSee": "markup",
      "SortAs": "SGML",
      "GlossDef": {
        "para": "A meta-markup language, used to create markup languages such as DocBook.",
        "GlossSeeAlso": [
          "GML",
          "XML"
        ]
      },
      "ID": "SGML",
      "Acronym": "SGML",
      "Abbrev": "ISO 8879:1986"
    }},
    "title": "S"
  }
}}

Reading a Json array from a String

Just like a JSONObject, JSONArray can also be read from a plain String using its constructor. Simply pass the source string to the constructor and it will build a JSONArray out of it.

You can operate the Json array using the same get and put methods described above.

package com.example.boot;

import org.json.JSONArray;

public class JsonArray {
    public static void main(String[] args) {
        JSONArray array = new JSONArray("[10,false,\"Arizona\",{\"key_one\":\"value_one\"}]");
        System.out.println(array.toString(2));
    }
}

Output

[
  10,
  false,
  "Arizona",
  {"key_one": "value_one"}
]