Srikanth Technologies

JSON Processing API in Java EE 7.0

In this blog, we will understand how to use JSON Processing API introduced in Java EE 7.0.

What is JSON?

JSON stands for JavaScript Object Notation. It is a format where we have objects with a set of name-value pairs. The following is an example for JSON object.

{"name" : "Mr. Srikanth",  "occupation" : "Director", "company" : "Srikanth Technologies"}

It is possible to have an object or an array within another object. The following example shows how to have an array of objects inside an object.

{ 
   "name" : "Mr. Srikanth",  "occupation" : "Director", "company" : "Srikanth Technologies",
   "contacts" : [  {"mobile" : "9059057000"}, { "email" : "srikanthpragada@yahoo.com"}]
}

JSON is preferred to XML when it comes to sending data as JSON is compact compared with XML.  JSON is widely used in  RESTful web services and AJAX.

It is also easy to process JSON object in JavaScript as JSON object can be converted to JavaScript object using eval() function in JavaScript.

JSON API

Though Java didn’t provide any API for JSON processing in the past, there were APIs provided by Google etc. I personally liked Google GSON library. The best part of it is; it can create JSON object from Java object or a Java collection (like ArrayList).

You can download GSON from here.

Java EE and JSON

Starting from Java EE 7.0, support for JSON Processing is provided by Java. It is called as JSON Processing in Java EE (JSR-353). This API allows Java programmer to do the following:

JSON API

The following are the classes and interfaces related to JSON API in Java EE.

Class or Interface Description
JsonContains static methods to create instances of JSON parsers, builders,generators. This class also contains methods to create parser, builder,and generator factory objects.
JsonReader Reads JSON data from a stream and creates an object model in memory.
JsonObjectBuilder,JsonArrayBuilder Creates an object model or an array model in memory by adding elements from application code.
JsonWriterWrites an object model from memory to a stream.
JsonValue,JsonStructure,JsonObject,JsonArray,JsonString,JsonNumberRepresents data types for elements in JSON data.
JsonParserRepresents an event-based parser that can read JSON data from a stream or from an object model.
JsonGenerator Writes JSON data to a stream one element at a time.

Using JSON Processing API

The following programs demonstrate how to create JSON API provided by Java EE 7.0.

Create JSON object using Object Model


import java.io.FileWriter;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

public class CreatJsonObject {

    public static void main(String[] args) throws Exception {

        JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add("name", "Srikanth");
        builder.add("occupation", "Director");
        builder.add("company", "Srikanth Technologies");

        JsonObject person = builder.build();

        StringWriter sw = new StringWriter();
        JsonWriter jw = Json.createWriter(sw);
        jw.writeObject(person);
        jw.close();
        System.out.println(sw.toString());
    }
}

When you run the above program, the following output is generated:

{"name":"Srikanth","occupation":"Director","company":"Srikanth Technologies"}

In case you want to write JSON object to a file, use the following code after you construct JsonObject:

   // write JSON object to a file -> c:\java\person.txt
        
   FileWriter fw = new FileWriter("c:\\java\\person.txt");
   JsonWriter fjw = Json.createWriter(fw);
   fjw.writeObject(person);
   fjw.close();
   fw.close();
        
   System.out.println("Wrote Object To File");

Creating JSON Array with Object Model

You can write an object that contains an array as shown in the following example. It creates an array with the name contacts and adds two objects to it.

import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

public class CreatJsonArray {

    public static void main(String[] args) {

        JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add("name", "Srikanth");
        builder.add("occupation", "Director");
        builder.add("company", "Srikanth Technologies");

       
        JsonArray contacts = Json.createArrayBuilder().add(
                Json.createObjectBuilder().add("email", "srikanthpragada@yahoo.com"))
                .add(Json.createObjectBuilder().add("mobile", "9059057000"))
                .build();

        builder.add("contacts", contacts); // contacts array

        JsonObject person = builder.build();

        StringWriter sw = new StringWriter();
        JsonWriter jw = Json.createWriter(sw);
        jw.writeObject(person);
        jw.close();

        System.out.println(sw.toString());
    } // main
 }
The output string is as follows:

{"name":"Srikanth","occupation":"Director","company":"Srikanth Technologies","contacts":[{"email":"srikanthpragada@yahoo.com"},{"mobile":"9059057000"}]}

Creating JSON Object using Generator

The following program creates an object using Generator.

import java.io.StringWriter;
import javax.json.Json;
import javax.json.stream.JsonGenerator;

public class UsingGenerator {
    public static void main(String[] args) {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = Json.createGenerator(sw);

        gen.writeStartObject()
                .write("name", "Srikanth Pragada")
                .write("email", "srikanthpragada@yahoo.com")
                .write("mobile", "34343434343")
                .writeEnd();

        gen.close();
        System.out.println(sw.toString());
    }
}

Creating JSON Array using Generator

The following program creates a JSON Array using Generator and writes JSON content into a file.

import java.io.FileWriter;
import javax.json.Json;
import javax.json.stream.JsonGenerator;

public class WriteArrayWithGenerator {

    public static void main(String[] args) throws Exception {

        FileWriter writer = new FileWriter("c:\\java\\persondetails.txt");
        JsonGenerator gen = Json.createGenerator(writer);
        gen.writeStartObject()
                .write("name", "Srikanth")
                .write("occupation", "Director")
                .write("company", "Srikanth Technologies")
                .writeStartArray("contacts")
                .writeStartObject()
                .write("email", "srikanthpragada@yahoo.com")
                .writeEnd()
                .writeStartObject()
                .write("mobile", "9059057000")
                .writeEnd() // for object
                .writeEnd() // for array
                .writeEnd(); // for root object
        gen.close();
    }
}

Read JSON Object using Object Model

JSON API allows reading JSON objects either using JsonReader or with JsonParser. This example shows how to use JsonReader.

import java.io.FileReader;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class DisplayPersonDetailsWithObjectModel {

    public static void main(String[] args) throws Exception {

        JsonReader reader = Json.createReader(new FileReader("c:\\java\\persondetails.txt"));
        JsonObject person = reader.readObject();
        
        System.out.println("Name       : "  +  person.getString("name"));
        System.out.println("Occupation : "  +  person.getString("occupation"));
        System.out.println("Company    : "  +  person.getString("company"));
        
        // display contacts
        JsonArray  contacts = person.getJsonArray("contacts");
        
        JsonObject jobj = contacts.getJsonObject(0);
        System.out.println("Email : " + jobj.getString("email"));
        
        jobj = contacts.getJsonObject(1);
        System.out.println("Mobile  : " + jobj.getString("mobile"));
    }
}

The output of the above program is as follows:

Name       : Srikanth
Occupation : Director
Company    : Srikanth Technologies
Email : srikanthpragada@yahoo.com
Mobile  : 9059057000

Reading JSON Object using Streaming API

The following program shows how to use JsonParser to parse JSON data and get one component at a time. It is left to us to determine the type of the event and handle it accordingly.

import java.io.FileReader;
import javax.json.Json;
import javax.json.stream.JsonParser;
public class DisplayPersonWithStreamAPI {
    public static void main(String[] args) throws Exception {
        JsonParser parser = Json.createParser(new FileReader("c:\\java\\person.txt"));
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch (event) {
                case KEY_NAME:
                    System.out.print( parser.getString() + ":"); 
                    break;
                case VALUE_STRING:
                    System.out.println(parser.getString());
                    break;
            }
        }
    }
}

Conclusion

With the introduction of API as part of Java EE 7.0, now it is possible to use standard API for JSON processing without having to resort to third party API.

This is just the beginning of JSON API in Java. There is scope for improvement. There are plans for next version. We need to wait a little longer to get more comprehensive JSON API from Java.