JSON with Java Example

This tutorial provides how to encode and decode JSON objects using Java programming language. JSON stands for JavaScript Object Notation. It is a simple and easy to understand, read and write data exchange format. It is very advanced and implemented in countless projects worldwide. For those who do not like XML; JSON is a very easy and different solution.

Setting up the environment

As a pre-requisite you will want to install any of the JSON module/package. Then download and install JSON.simple . You may need to add the location of json-simple jar file to the CLASSPATH:

The JSON.simple library plots from the left side to the right side while decoding or parsing. It plots entities from the right to the left while decoding.

string String ( java.lang library)
number Number ( java.lang library)
true|false Boolean ( java.lang library)
null null
array List ( java.util library)
object Map ( java.util library)


For decoding, the  class of Map is org.json.simple.JSONObject and for List it is org.json.simple.JSONArray.

Java API for JSON Processing

JSON provides two structured type – objects and arrays. An object is a real world entity such as zero or more name /value pairs. The array is an ordered sequence of zero or more values. These value can be strings, numbers, Booleans, null, and their two structured types.

An example from Wikipedia that display the JSON defined of an object that explain about a person. Object has string values for first name and last name, a number value for age, object value describes the person residential address and an array value of phone number objects.

    "firstName": "Meraj",
    "lastName": "Ansari",
    "age": 20,
    "address": {
        "streetAddress": "Gonda India",
        "city": "INDIA",
        "state": "UP",
        "postalCode": 224001
    "phoneNumbers": [
            "type": "Mobile",
            "number": "09839810502"
            "type": "home",
            "number": "09170441603"



JSON is widely used in Ajax applications, configurations, databases, and RESTful web services. Popular websites provide JSON as the data exchange format with their RESTful web services.

The JSON Processing

Java Application Programming Interface (API) for JSON processing (JSR 353) offer portable APIs to parse, transform, and query JSON with object model and streaming Application Programming Interface.

The object model API provides how to create a random–access like tree structure that defines the JSON data memory.

A streaming API provides how to parse and generate JSON in a streaming way. These techniques do parsing and generation control to the programmer. Streaming Application Programming Interface is an event based parser and offers an application developer to say for the next occasion rather than performing the task during a method call. Developers are given more interactive control over the JSON processing. The application codes or process or discards the parser event, say for the next event. The streaming model is providing local processing where randomly access of other parts of the data is not required.  We can say the streaming API provides a way to implement well-formed JSON to a stream by writing one event at a time.

Encoding JSON in Java

Here we are giving a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. This is no sequencing provided. If you want to strict sequencing of elements use JSONValue.toJSONString (map) method with ordered map like the  java.util.LinkedHashMap.

import org.json.simple.JSONObject;
class JsonEncodeFirst
   public static void main(String[] args)
      JSONObject obj = new JSONObject();
      obj.put("name", "Meraj");
      obj.put("num", new Integer(100));
      obj.put("balance", new Double(2000.31));
      obj.put("is_vip", new Boolean(true));
StringWriter out = new StringWriter();
String jsonText = out.toString();

After compile and executing above program this will provide following output.

{"balance": 2000.31, "num":100, "is_vip":true, "name":"Meraj"}

Decoding JSON in Java

Here we are giving a simple that makes use of JSONObject and JSONArray where is JSONObject a java.util.Map and JSONArray is a java.util.List, so we can access them with standard operation of Map and List.

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeFirst2
   public static void main(String[] arv)
      JSONParser parserInteger=new JSONParserInteger();
      String s = "m,”e,”r,”a,”j,”}};
         Object obj = parser.parse(s);
         JSONArray array = (JSONArray)obj;
         System.out.println("The 2nd letter of array");
         JSONObject obj2 = (JSONObject)array.get(s);
         System.out.println("position \"1\"");
         s = "{}";
         obj = parser.parse(s);
         s= "[j,]";
         obj = parser.parse(s);
         s= "[j,,r]";
         obj = parser.parse(s);
      }catch(ParseException pe){
         System.out.println("size: " + pe.getSize(s));

After compile and executing this program this will provide following output:

The 2nd letter of array
Field "1"