How can we decode a JSON object in Java?


A JSON is a lightweight, text-based and language-independent data exchange format. A JSON can represent two structured types like objects and arrays. We can decode a JSON object using JSONObject and JSONArray from json.simple API. A JSONObject works as a java.util.Map whereas JSONArray works as a java.util.List.

In the below example, we can decode a JSON object.

Example

import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONDecodingTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      String str = "[ 0 , {\"1\" : { \"2\" : {\"3\" : {\"4\" : [5, { \"6\" : { \"7\" : 8 } } ] } } }    } ]";
      try {
         Object obj = parser.parse(str);
         JSONArray array = (JSONArray)obj;
         System.out.println("2nd Array element: ");
         System.out.println(array.get(1));
         System.out.println();
         JSONObject object2 = (JSONObject) array.get(1);
         System.out.println("Field \"1\"");
         System.out.println(object2.get("1"));
         str = "{}";
         obj = parser.parse(str);
         System.out.println(obj);
         str = "[6,]";
         obj = parser.parse(str);
         System.out.println(obj);
         str = "[6,,3]";
         obj = parser.parse(str);
         System.out.println(obj);
      } catch(ParseException parseExp) {
           System.out.println("Exception position: " + parseExp.getPosition());
           System.out.println(parseExp);
      }
   }
}

Output

2nd Array element:
{"1":{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}
{}
[6]
[6,3]

Updated on: 04-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements