September 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

JSON Processing in Java EE 7

  • January 29, 2014
  • By Manoj Debnath
  • Send Email »
  • More Articles »

JavaScript Object Notation (JSON) is a lightweight language independent data interchange format used for enterprise messaging or B2B communication much like XML. Defined within the artifact of JCP(JSR 353), the standard Java API was released with Java EE7. This API is named JSON-P. The specification provides a mechanism to transform, query, generate and parse JSON data.  JSON is more readable and closely related to JavaScript as the name suggests. Due to its inherent JavaScript quality, it is directly consumable in a web page. This is one of the main reasons why JSON is gaining popularity over XML in the enterprise scenario, especially in consuming and creating web services.

JSON Structure

Similar to XML, it is represented in plain textual format. The data structure uses a set of simple conventions much like Java classes to represent data. A typical JSON structure can be built as:

  • A collection of name/value pairs
  • An ordered list of values

For example a JSON representation of an object can be as follows (Listing 1):

Listing 1: JSON structured

{
       "book":{
             "isbn" : "12356789",
             "title" : "Algorithm",
             "author" : [
                           "Cormen",
                           "Rivest",
                           "Stein"
             ],
             "price" : 45.78
       }
}

Unlike XML, JSON also represents quite a few primitive and structured data types. Such as,

  • Number: primitive type to declare a number in JSON represented without quotes
  • String: an array of zero or more unicode characters represented within quotes
  • Value: values represented by true, false, null, double quoted string, object, array
  • Array: ordered set of values encompassed within brackets, [ , ] and values separated by comma.
  • Object: ordered set of name/value pairs as defined within the parenthesis, { }

JSON Processing

There is whole bunch of third party Java based libraries to process Java objects to and from JSON. The list can be found at json.org. JASON-P is the name given to standard Java API for processing. Perhaps, JASON-B is slated to be released in the future for binding Java objects to JASON data as currently there is no such feature like JAXB. Similar to DOM and SAX API of XML processing, JSON provides two programming models:

1. Object Model API: Like DOM API, Object Model API uses builder pattern to model JSON objects as a tree structure to represent data in memory. The model provides the JsonReader interface for consuming JSON objects and JsonObjectBuilder and JsonArrayBuilder to produce JSON objects.

2. Streaming API: This API is similar to SAX API for XML and used for parsing JSON text in a streaming fashion. It is a low-level, event-based API based on pull parsing streaming model. Unlike Object Model API, it is less memory intensive and hence suitable for processing a large amount of JSON data.

Object Model API: Consuming JSON

JsonObject can be created from a JSON source file using javax.json.JsonReader. JsonObject provides the mapping view of the name/value pairs. JsonReader reads the JSON object from an input source. Json class provides createReader methods to create the reader object from the input source.

Listing 2: Consuming JSON data

try{
       JsonReader jsonReader = Json.createReader(new FileReader("book.json"));
       JsonObject jsonObject = jsonReader.readObject();
       jsonObject = jsonObject.getJsonObject("book");
}catch(FileNotFoundException ex){}
 
 

Object Model API: Producing JSON

JSON objects can be created using classes javax.json.JsonObject and javax.json.JsonArray. As shown in  Listing 2, the method createObjectBuilder actually returns JsonObjectBuilder and its subsequent add methods can be used to create hierarchical JSON data dynamically. The following code creates an array of authors within the JSON object 'book'.

Listing 3: Producing JSON data

public class BookJsonBuilder
       public JsonObject buildBook(){        
             return Json.createObjectBuilder()
                           .add("book", Json.createObjectBuilder()
                           .add("isbn", "12356789")
                           .add("title", "Algorithm")
                           .add("author", Json.createArrayBuilder()
                                        .add("Cormen")
                                        .add("Rivest")
                                        .add("Stein"))                                        
                           .add("price",45.78)).build();
       }
}
 

Streaming API: Consuming JSON

JsonParser is the interface that provides read-only access to JSON data. Json class provides the method to create a parser from sources InputStream or Reader to consume data in streaming way. The following code demonstrates how to parse the JSON data of Listing 1, if the input source is a JSON data file named 'book.json'

Listing 4: Consuming JSON data

public class BookJsonParser {   
       public String parseBookAndGetTitle() {
       String title = "";
       try {
             JsonParser parser = Json.createParser(new FileReader("book.json"));
             while (parser.hasNext()) {
                    JsonParser.Event event = parser.next();
                    while (parser.hasNext()
                           && !(event.equals(JsonParser.Event.KEY_NAME) 
                           && parser.getString().matches("title"))) {
                                  event = parser.next();
                           }
                           if (event.equals(JsonParser.Event.KEY_NAME)
                                        && parser.getString().matches("title")) {
                                  parser.next();
                                  title = parser.getString();
                           }
                    }
             } catch (FileNotFoundException ex) {}
             return title;
       }
}
 

Streaming API: Producing JSON

JsonGeneratorFactory provides an event-based method to write  name/value pairs to a streaming object. JsonParser is basically used for parsing streaming JSON objects while JsonGenerator is used for writing JSON to a streaming based on each event.

Listing 5: Producing JSON data

JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
JsonGenerator generator = factory.createGenerator(System.out);
generator.writeStartObject()
      .write("isbn","12356789")
      .write("title","Algorithm")
      .writeStartArray("author")
            .write("Cormen")
            .write("Rivest")
            .write("Stein")
      .writeEnd()
      .write("price","45.78")      
.writeEnd();
 
 

Conclusion

We can see that in most cases XML and JSON serve a similar purpose, but what makes developer bias in favor of JSON? JSON is lightweight and faster than XML in the sense, processing is hassle free and comparatively quick. Extracting values in XML requires one to loop through DOM/SAX throughout the document and store the values in the variable whereas in the case of JSON, fetch the string and evaluate the name value pairs – simple and straight forward. Only vantage point, I believe, that goes in favor of XML is that it is a mature, extensively used until now and a veteran in the field of data interchange. JSON is a new idea and its presence is already felt in the community, which is the reason why it crept into the Java EE7 specification; more will be felt in its future releases, I believe. So the question arises, is JSON going to replace XML? Only time will tell.


Tags: JavaScript, JSON, JSONP, Java EE 7




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel