Write and Parse JSON in JAVA

JSONParse JSON in JAVAWrite JSON in JAVA

JSON is a simple text data format as well as it is not dependent on any language. In many programming languages, JSON parsers and generator libraries are readily available. Let's discuss how to write and read JSON in JAVA.

Consider the following sample JSON Document :

{
    "name" : "File.mp3",
    "size" : "25Mb",
    "section" : [ 1 , 2, 3 , 4 ],
    "updateby" : [
     {
         "name" : "user one",
         "date" : "10:00 21 May",
         "userrole" : [ "add", "update", "delete"]
     },
     {
         "name" : "user two",
         "date" : "10:00 21 May",
         "userrole" : [ "add", "delete"]
     }],
    "Metadata" : { "create" : "21 MAy", "audio" : "acc", "video" : "H264"}
}

JSON mainly creates two structures: A collection of name-value pairs and a List of values. In the above JSON Document name and size are key and value pairs, updateby and section are the list of values, Value of updateby and Metadata cover as a nested form of key-value or list of values.

Setup

There are many jars readily available in JAVA. Here will use Org-JSON to write the above object in JAVA. For this, we need to add the following dependency in our maven project or download an imported jar in the Java project. Click here to get the updated jar.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>**Version</version>
</dependency>


Write JSON in JAVA

STEP 1: To write JSON, First you need to import a JSON Jar and create a JSON Object.

import org.json.*;
JSONObject jsonObj = new JSONObject();

STEP 2: For Key value pairs, we can put the key and respective value in the created object.

jsonObj.put("name", "File.mp3");
jsonObj.put("size", "25Mb");

STEP 3: To Create a JSON Array, we need to use JSONArray Class.

JSONArray jsonArray = new JSONArray();
jsonArray.put(4);
jsonArray.put(1);
jsonArray.put(2);
jsonArray.put(3);

To insert JSON Array in JSON Object, we need to use the same put() method.

jsonObj.put("section", jsonArray);

STEP 4: Similarly we can add JSON Object in JSON Object or we can create a JSON Object array.

JSONObject metaDataJsonObj = new JSONObject();
metaDataJsonObj.put("create", "21 MAy");
metaDataJsonObj.put("audio", "acc");
metaDataJsonObj.put("video", "H264");
//Add JSON object to the JSON object as a value
jsonObj.put("metadata", metaDataJsonObj);

Let’s see a complete code of write JSON data :

package JsonCreat;

import org.json.*;

public class JsonCreat {

  public JSONObject jsonCreat() {

    // creating JSON Object
    JSONObject jsonObj = new JSONObject();

    // creating key value pair JSON Object
    jsonObj.put("name", "File.mp3");
    jsonObj.put("size", "25Mb");

    //Creating a JSON Array
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(1);
    jsonArray.put(2);
    jsonArray.put(3);
    jsonArray.put(4);

    //Adding array to the JSON object as a value
    jsonObj.put("section", jsonArray);

    // creating JSON Object
    JSONObject updateListJsonObj_one = new JSONObject();
    updateListJsonObj_one.put("name", "");
    updateListJsonObj_one.put("date", "");

    //Creating a JSON Array
    JSONArray userRoleJsonArray_one = new JSONArray();
    userRoleJsonArray_one.put("add");
    userRoleJsonArray_one.put("update");
    userRoleJsonArray_one.put("delete");

    //Adding array to the JSON object as a value
    updateListJsonObj_one.put("userrole", userRoleJsonArray_one);

    // creating JSON Object
    JSONObject updateListJsonObj_two = new JSONObject();
    updateListJsonObj_two.put("name", "");
    updateListJsonObj_two.put("date", "");

    //Creating a JSON Array
    JSONArray userRoleJsonArray_two = new JSONArray();
    userRoleJsonArray_two.put("add");
    userRoleJsonArray_two.put("delete");

    //Adding array to the JSON object as a value
    updateListJsonObj_two.put("userrole", userRoleJsonArray_two);

    // Creating a JSON Array for adding  userRoleJsonArray_one and userRoleJsonArray_two as a value of "updateby"
    JSONArray updateByJsonArray = new JSONArray();
    updateByJsonArray.put(updateListJsonObj_one);
    updateByJsonArray.put(updateListJsonObj_two);

    //Adding array to the JSON object as a value
    jsonObj.put("updateby", updateByJsonArray);

    // creating JSON Object
    JSONObject metaDataJsonObj = new JSONObject();
    metaDataJsonObj.put("create", "21 MAy");
    metaDataJsonObj.put("audio", "acc");
    metaDataJsonObj.put("video", "H264");

    //Adding JSON object to the JSON object as a value
    jsonObj.put("metadata", metaDataJsonObj);

    //Print JSON
    System.out.println("Output JSON : ");
    System.out.println(jsonObj.toString());
    return jsonObj;
  }
}


Parse JSON in JAVA

STEP 1: To parse JSON, First you need to import a JSON Jar and create a JSON Object with JSON String argument.

import org.json.*;

String jsonData = "{"name":"File.mp3","size":"25Mb","section":[1,2,3,4],"updateby":[{"name":"user one","date":"10:00 21 May","userrole":["add","update","delete"]},{"name":"user two","date":"10:00 21 May","userrole":["add","delete"]}],"Metadata":{"create":"21 MAy","audio":"acc","video":"H264"}}";

JSONObject jsonObject = new JSONObject(jsondata);

STEP 2: To read all the keys, we need to take an iterator.

Iterator keys = jsonObject.keys();

STEP 3: Initialize any control flow statement to extract data from Object.

while(keys.hasNext())
{ ...

To identify data type we can use instanceof keyword, for example

//To Identify JSON Object
jsonObject.get(key) instanceof JSONObject;

//To Identify String
jsonObject.get(key) instanceof String;

Let’s see a complete code of parse JSON data :

package JsonParser;

import java.util.Iterator;

import org.json.*;

public class JsonParser {

  public void jsonParser(String jsondata) {

    // pars string in JSON Object
    JSONObject jsonObject = new JSONObject(jsondata);

    //Gets all key from JSON object
    Iterator keys = jsonObject.keys();

    System.out.println(" ");
    System.out.println("Parse JSON : ");

    while(keys.hasNext()) {
        String key = keys.next();
        if (jsonObject.get(key) instanceof JSONObject) {
          JSONObject jsonObjectData = (JSONObject) jsonObject.get(key);
          System.out.println("JSON Value is a Object : " + jsonObjectData);
        } else if(jsonObject.get(key) instanceof JSONArray) {
          JSONArray jsonArrayData = (JSONArray) jsonObject.get(key);
          System.out.println("JSON Value is a Array : " + jsonArrayData);

          //iterating JSON Array
          Iterator iterator = jsonArrayData.iterator();
          while(iterator.hasNext()) {
             Object _dataObj = iterator.next();
             if (_dataObj instanceof JSONObject) {
               //Can process as JSON Object**
               System.out.println(" 	Array of Json Object value is : " + _dataObj);
             } else if(_dataObj instanceof Integer) {
               System.out.println(" 	Integer Array value is : " + _dataObj);
             }
          }
        } else if(jsonObject.get(key) instanceof String) {
          System.out.println("JSON Value is a String : " + jsonObject.get(key).toString());
        } else if(jsonObject.get(key) instanceof Integer) {
          System.out.println("JSON Value is a Integer : " + jsonObject.get(key).toString());
        }
    }
  }
}

Download


JSON In Java Jar : Click here

JSON.simple Jar : Click here

Source Code : Click here

Credits


JSON In Java Jar - Java JSON encoders/decoders package

json.org - Introducing JSON Standard