Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Exploring the JavaScript Object Notation - JSON

In this article we will see all the main points regarding JSON notation: the most used notation for JavaScript.

JSON or Java Script Object Notation is used as a data-interchange format which is very lightweight and has the ability to replace XML where ever required. The data-interchange format is used to transfer data or information from one source to another which belongs to incompatible technological families. Let us consider an example where the sender application is a Java based system running on a Unix platform while the receiver could be a Visual Basic program running on standard Windows platform.

In this situation, in order to send some data from one platform to another we would require a standard format to send the data across since these applications can never communicate directly amongst them. Even if these two could communicate over some protocols like TCP/IP or FTP, the data structures has to be defined at some place or the other. This is where the data-interchange or data exchange format pitches in. When XML got introduced in the industry in the late nineties, it was considered as a revolution in the IT industry since it was very intuitive to be looked upon and at the same time it was based on the HTML language which was widely known at that point of time.

Though XML gave the liberty to the developers to communicate using different technologies, it turned out that parsing the XML was not an easy task. Most developers today have to go thru a learning curve on how to handle the tags, despite the fact that there are array of libraries which can take up many common tasks which starts from extracting node attributes and goes up to searching for specific data in the hierarchy. Web developers used to face a similar situation while dealing with dynamic HTML content in the early days. While XML was made to support the data transfer from one application to another, the format for it was derived from the Standard Generalized Markup Language or SGML, which has a close resemblance to HTML as compared to any other programming language.

Though flexible but it is equally cumbersome in any language. JSON has an advantage here since it doesn't share this concept as it is based on the standard programming concepts which are common in the C family of programming languages that includes C, C++, C#, Java, JavaScript, Perl, Python and many others. JSON is also more successful when compared to the than tag based XML language. In the later sections of this document we are going to realize the fact that JSON as a subset of the JavaScript has many advantages while dealing with Web applications, where a lot of data exchange between different technological families takes place. It must also be noted that JSON is very well suited while dealing with AJAX calls.

Objectives and Goals of JSON

The objective or goal to have JSON is to represent an object into a meaningful and standard manner which can be easily understood by the humans. At the same time it should be rapidly parsed by applications. This is achieved by formatting the object as a string representation using the commonly used programming syntax characters. This is easily understood by the programmers as they are very much familiar to these characters. For instance, any developer knows well how to define and read an integer data type - 'int varName = 3' while a string is declared as - 'String varName = "abc"'. Most programming languages have the ability to represent much more complicated data types e.g arrays using literals such as: "var arrayLiteral = [1, '2', 3.45, 'animal'];" . It must be noted here that the array contains several data types as well, depending on the language if it is supported.

JSON Specifications

Let us talk about the specifications of JSON standard.

In JSON, the objects are separated by using curly braces "{ }". Any developer would initially get confused with the JavaScript interpreter as in JavaScript these curly braces are used to enclose a function body. The JSON based signature is organized in the standard key-value pair which is used to represent the data. The key and its corresponding value are separated by a colon character ':’ as shown below -

Listing 1 - JSON representation

  Syntax - 
  "key": value
  String Example
  "name": "John"
  Numeric  Example
  "price": 55.99
  

In the above example, we can see that the word 'John' is enclosed within quotes which indicate that it is a String data type; while the numeric value is not required to be enclosed within any quote which is quite similar to any programming language. In JSON, the Keys and String values are always enclosed within double quotes. It is a standard practice in the JSON world to have the keys enclosed within quotes. JSON supports almost all types of data which includes the following –

  • number - that could be integer, real, or floating point.
  • String - This could be double-quoted Unicode with or without a backslash as an escape character.
  • boolean - This could be either true or false.
  • Array – This could be an ordered sequence of values, comma-separated and also enclosed within square brackets
  • Object - (collection of key/value pairs, comma-separated and enclosed in curly brackets)

Here is a sample JSON object demonstrating various data types:

Listing 2 - A Sample JSON string

{ "anInt" : 4567, "aFloat" : 87.654, "aString" : " A Test text",  "aBoolean" : true,   "anArray" :  [1,  "2",  3.45,  "animal"],  "anObject" : { "prop1" :  "a value",  "prop2" :  "another value" ,  "prop3" :  -9999 } "aNull": null }

JSON Parsing

As with any data exchange format, JSON also has to undergo the parsing mechanism. In this document, I will talk about some of the Java based JSON parsers available in the market. These are listed as below -

Jackson Parser -

The Jackson library is a multi-purpose Java library used to processing JSON which presents the best possible combination of being fast, accurate and lightweight for developers. Jackson also offers three methods for processing JSON as listed under -

  • Streaming API or incremental parsing/generation: This method reads and writes all JSON content as discrete events
  • Tree model: This method provides a mutable and in-memory tree representation of a JSON document
  • Data binding: It converts JSON to and from POJO’s, which is plain old java objects

In this document we are interested to convert a POJO into JSON and vice versa. We need to have the following three libraries before we start -

  • jackson annotation library
  • jackson core library
  • jackson binding library

Let us consider the following POJO object which we are going to represent as JSON format and vice versa –

Listing 3 - A Simple POJO Class

  package com.home.json.vo;
   
  import java.util.List;
   
  public class ValObject {
   
      private int age;
      private String name;
      private List<String> messages;
      private String message;
      
      /**
       * @return the age
       */
      public int getAge() {
          return age;
      }
      /**
       * @param age the age to set
       */
      public void setAge ( int age ) {
          this.age = age;
      }
      /**
       * @return the name
       */
      public String getName () {
          return name;
      }
      /**
       * @param name the name to set
       */
      public void setName ( String name ) {
          this.name = name;
      }
      /**
       * @return the messages
       */
      public List<String> getMessages () {
          return messages;
      }
      /**
       * @param messages the messages to set
       */
      public void setMessages ( List <String> messages ) {
          this.messages = messages;
      }
      /**
       * @return the message
       */
      public String getMessage () {
          return message;
      }
      /**
       * @param message the message to set
       */
      public void setMessage ( String message ) {
          this.message = message;
      }
  }
   
  

Listing 4 - The Jackson based parser class.

  package com.home.json.parse;
   
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.List;
   
  import com.fasterxml.jackson.core.JsonGenerationException;
  import com.fasterxml.jackson.databind.JsonMappingException;
  import com.fasterxml.jackson.databind.ObjectMapper;
  import com.home.json.vo.ValObject;
   
  public class JacksonBasedParser {
   
      public JacksonBasedParser() {
          ValObject valObj = new ValObject ();
          valObj.setAge( 44 );
          valObj.setName( " Stuart Campbell ");
          List<String> messages = new ArrayList<String>() {
              {
                  add( " You are required to be at the airport by 7:00 AM." );
                  add( " You will meet a person called Harish Salvekar." );
                  add( " He will handover your tickets and other travel documents." );
              }
          };
          valObj.setMessages ( messages );
          System.out.println( " JSON STRING = " + toJSON(valObj) );
   
          String JSON_STRING = " { \"age\": 64, \"name\": \"Daine Campbell\", \"messages\" :[ \"You are required to be at the airport by 8:00 PM.\", \"You will meet a person called Minakshi Salvekar.\", \"She will handover your tickets and other travel documents.\" ]}";
          
          ValObject valuObject = fromJSON( JSON_STRING );
          System.out.println(" **********************DATA FROM OBJECT********************************** ");
          System.out.println(" ************ AGE = "+valuObject.getAge()+" ***************************** ");
          System.out.println(" *********** NAME = "+valuObject.getName()+" **************************** ");
          for (String singleMsg : valuObject.getMessages()) {
              System.out.println(" *********** Message = " +singleMsg +"******************************** ");
          }
   
      }
   
      public String toJSON(ValObject valObject) {
          String JSONStr = "";
   
          try {
              ObjectMapper mapper = new ObjectMapper();
              JSONStr = mapper.writeValueAsString(valObject);
          } catch (JsonGenerationException e) {
          } catch (JsonMappingException e) {
          } catch (IOException e) {
          }
   
          return JSONStr;
      }
   
      public ValObject fromJSON( String jsonStr ) {
          ValObject valObj = null;
          try {
              ObjectMapper mapper = new ObjectMapper ();
              valObj = mapper.readValue( jsonStr, ValObject.class );
          } catch (IOException e) {
              e.printStackTrace ();
          }
          return valObj;
      }
   
      public static void main( String[] args ) {
          new JacksonBasedParser();
      }
   
  }
  

On executing this class we get the following output –

Listing 5 - Output of the Jackson based parser class

  JSON STRING = { "age" : 44,"name" : "Stuart Campbell", "messages" :["You are required to be at the airport by 7:00 AM.", "You will meet a person called Harish Salvekar.", "He will handover your tickets and other travel documents."]}
  **********************DATA FROM OBJECT**********************************
  ************ AGE = 64 *****************************
  *********** NAME = Daine Campbell ****************************
  *********** Message = You are required to be at the airport by 8:00 PM.********************************
  *********** Message = You will meet a person called Minakshi Salvekar.********************************
  *********** Message = She will handover your tickets and other travel documents.********************************
  

So, now in the above code sample we have seen how to create a JSON string from a POJO object and also how to convert a POJO object into a JSON String using the Jackson library.

GSON Parser

GSON stands for google-gson. Gson is a Java library which has the capability of converting the Java objects into their JSON representation and the corresponding JSON strings to an equivalent POJO object without placing Java annotations in the corresponding classes. Gson comes up with the following characteristics -

  • It has the ability to provide simple toJson and fromJson methods which are used to convert Java objects to JSON and vice-versa
  • It has the ability to convert the pre-existing immutable objects to and from JSON
  • It supports Java Generics extensively.
  • It also supports arbitrarily complex objects.

The above code can be modified to use the GSON parser as under -

Listing 6 - The GSON based parser class

  package com.home.json.parse;
   
  import java.util.ArrayList;
  import java.util.List;
   
  import com.google.gson.Gson;
  import com.home.json.vo.ValObject;
   
  public class GSONBasedParser {
   
      public GSONBasedParser() {
          ValObject valObj = new ValObject ();
          valObj.setAge(64);
          valObj.setName( " Daine Campbell ");
          List<String> messages = new ArrayList<String>() {
              {
                  add( " You are required to be at the airport by 8:00 PM. " );
                  add( " You will meet a person called Minakshi Salvekar. " );
                  add( " She will handover your tickets and other travel documents. " );
              }
          };
          valObj.setMessages(messages);
          System.out.println( " JSON STRING = " + toJSONObj(valObj) );
   
          String JSON_STRING = "{ \"age\" : 64, \"name\" :\"Daine Campbell\", \"messages\" :[\ "You are required to be at the airport by 8:00 PM.\", \" You will meet a person called Minakshi Salvekar.\", \"She will handover your tickets and other travel documents.\" ]}";
   
          ValObject valuObject = fromJSONObj(JSON_STRING);
          System.out.println("DATA FROM OBJECT  ");
          System.out.println("AGE = " + valuObject.getAge() + " ");
          System.out.println("NAME = " + valuObject.getName() + "  ");
          for (String singleMsg : valuObject.getMessages()) {
              System.out.println("Message = " + singleMsg + " ");
          }
      }
   
      public String toJSONObj (ValObject valObject) {
          String JSONStr = "";
          Gson gson = new Gson();
          JSONStr = gson.toJson(valObject);
   
          return JSONStr;
      }
   
      public ValObject fromJSONObj(String jsonStr ) {
          ValObject valObj = null;
          Gson gson = new Gson();
          valObj = gson.fromJson( jsonStr, ValObject.class );
   
          return valObj;
      }
      
      public static void main ( String[] args ) {
          new GSONBasedParser();
      }
   
  }
   

On executing this class we get the following output –

Listing 7 - Output of the GSON based parser class.

  JSON STRING = { " age" : 64,"name" : "Daine Campbell", "messages": ["You are required to be at the airport by 8:00 PM.","You will meet a person called Minakshi Salvekar.","She will handover your tickets and other travel documents." ]}
  DATA FROM OBJECT 
  AGE = 64 
  NAME = Daine Campbell Message = You are required to be at the airport by 8:00 PM.
  Message = You will meet a person called Minakshi Salvekar
   Message = She will handover your tickets and other travel documents
   </p>
  <h3>JSON Lib Parser</h3>
  <p>
  JSON-lib is a Java library. It has the capability to transform Java beans, maps, collections, java arrays and XML into JSON and also the reverse. JSON-lib can be downloaded from http://sourceforge.net/projects/json-lib/files/ and it depends on the following libraries - 
  jakarta commons-lang 2.6jakarta commons-beanutils 1.9.1jakarta commons-collections 3.2.1jakarta commons-logging 1.1.3ezmorph 1.0.6
Let us have a look how this library works. We will modify the same code to use this library.

Listing 8 - The JSON lib based parser class.

  package com.home.json.parse;
   
  import java.util.ArrayList;
  import java.util.List;
   
  import net.sf.json.JSONArray;
  import net.sf.json.JSONObject;
  import net.sf.json.JSONSerializer;
   
  import com.home.json.vo.ValObject;
   
  public class JSONLibBasedParser {
   
      public JSONLibBasedParser() {
          ValObject valObj = new ValObject();
          valObj.setAge(54);
          valObj.setName( " Roger Campbell ");
          List<String> messages = new ArrayList<String>() {
              {
                  add( " You are required to be at the airport by 9:00 PM. ");
                  add( " You will meet a person called Gautam Salvekar. ");
                  add( " He will handover your tickets and other travel documents. ");
              }
          };
          valObj.setMessages(messages);
          System.out.println("JSON STRING = " + toJSONObj(valObj));
   
          String JSON_STRING = "{ \"age\" : 54,\ "name\" : \"Roger Campbell\", \"messages\" :[\"You are required to be at the airport by 9:00 PM.\",\"You will meet a person called Gautam Salvekar.\", \"He will handover your tickets and other travel documents.\" ]}";
   
          ValObject valuObject = fromJSONObj(JSON_STRING);
          System.out.println("DATA FROM OBJECT ");
          System.out.println("AGE = " + valuObject.getAge() + " ");
          System.out.println("NAME = " + valuObject.getName() + " ");
          for (String singleMsg : valuObject.getMessages()) {
              System.out.println("Message = " + singleMsg + "");
          }
      }
   
   
      private String toJSONObj(ValObject valObj) {
          String JSONStr = "";
          JSONStr = JSONSerializer.toJSON(valObj).toString(); 
          return JSONStr;
      }
   
      private ValObject fromJSONObj(String jSON_STRING) {
          ValObject valObj = new ValObject();
          JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( jSON_STRING );  
          valObj.setAge(jsonObject.getInt( "age" ));
          valObj.setName(jsonObject.getString( "name" ));
          JSONArray messageArr = jsonObject.getJSONArray( "messages" );
          List<String> msgList = new ArrayList<String> ();
          for (int i = 0; i < messageArr.size(); i++) {
              String megObj = (String)messageArr.get(i);
              msgList.add(megObj);
          }
          valObj.setMessages(msgList);
          
          return valObj;
      }
      
      public static void main(String[] args) {
          new JSONLibBasedParser();
      }
  }
  

Listing 9 - Output of the JSON lib based parser class.

  JSON STRING = {"name":"Roger Campbell","messages":["You are required to be at the airport by 9:00 PM.","You will meet a person called Gautam Salvekar.","He will hand over your tickets and other travel documents."],"age":54}
  ############################ DATA FROM OBJECT ############################
  ############################ AGE = 54 ############################
  ############################ NAME = Roger Campbell ############################
  ############################ Message = You are required to be at the airport by 9:00 PM.############################
  ############################ Message = You will meet a person called Gautam Salvekar.############################
  ############################ Message = He will handover your tickets and other travel documents.############################
  

FlexJSON Parser

FlexJSON is a lightweight library for parsing. It is used to serialize and de-serialize Java objects into and from JSON structure. It allows deep and shallow copy of the objects. The depth to which an object is to be serialized is controlled with the help of Flexjson libraries. Here we are modifying our POJO object as under -

Listing 10 - Modified POJO class

  package com.home.json.vo;
   
  import java.util.List;
   
  public class ValueObject {
   
      private int age;
      private String name;
      private String message;
      
      /**
       * @return the age
       */
      public int getAge() {
          return age;
      }
      /**
       * @param age the age to set
       */
      public void setAge(int age) {
          this.age = age;
      }
      /**
       * @return the name
       */
      public String getName() {
          return name;
      }
      /**
       * @param name the name to set
       */
      public void setName(String name) {
          this.name = name;
      }
      
      /**
       * @return the message
       */
      public String getMessage() {
          return message;
      }
      /**
       * @param message the message to set
       */
      public void setMessage(String message) {
          this.message = message;
      }
  }
  

Listing 11 - The FlexJSON based parser class.

  package com.home.json.parse;
   
  import java.io.Writer;
   
  import com.home.json.vo.ValObject;
  import com.home.json.vo.ValueObject;
   
  import flexjson.JSONDeserializer;
  import flexjson.JSONSerializer;
   
  public class FlexJSONBasedParser {
   
      public FlexJSONBasedParser() {
          ValueObject valObj = new ValueObject();
          valObj.setAge(64);
          valObj.setName("Daine Gandhi");
          valObj.setMessage("You are required to be at the airport by 10:00 PM. "
                  + "You will meet a person called Minakshi Campbell."
                  + "She will handover your tickets and other travel documents.");
          System.out.println("JSON STRING = " + toJSONObj(valObj));
   
          String JSON_STRING = "{\"age\":64,\"name\":\"Daine Gandhi\",\"message\":\"You are required to be at the airport by 10:00 PM. You will meet a person called Minakshi Campbell. She will handover your tickets and other travel documents.\"}";
   
          ValueObject valuObject = fromJSONObj(JSON_STRING);
          System.out.println("DATA FROM OBJECT ");
          System.out.println("AGE = " + valuObject.getAge() + " ");
          System.out.println("NAME = " + valuObject.getName() + " ");
          System.out.println("Message = " + valuObject.getMessage() + "");
      }
   
      private ValueObject fromJSONObj(String jSON_STRING) {
          ValueObject valuObject = null;
          JSONDeserializer<ValueObject> deserializer = new JSONDeserializer<ValueObject>();
          valuObject = deserializer.deserialize(jSON_STRING, ValueObject.class);
          return valuObject;
      }
   
      private String toJSONObj(ValueObject valObj) {
          String JSONStr = "";
          JSONSerializer serializer = new JSONSerializer();
          JSONStr = serializer.serialize(valObj);
          return JSONStr;
      }
      
      public static void main(String[] args) {
          new FlexJSONBasedParser();
      }
   
  }
  

Listing 12 - Output of the JSON lib based parser class.

  JSON STRING = {"age":64,"message":"You are required to be at the airport by 10:00 PM. You will meet a person called Minakshi Campbell.She will handover your tickets and other travel documents.","name":"Daine Gandhi"}
  DATA FROM OBJECT 
  AGE = 64 NAME = Daine Gandhi 
  Message = You are required to be at the airport by 10:00 PM. You will meet a person called Minakshi Campbell. She will handover your tickets and other travel documents
  

JSON IO Parser

JSON IO library is another Java library which is able to process JSON. Json-io comes with two major classes, a reader and a writer, which eliminates the need to use ObjectInputStream and ObjectOutputStream that are required to serialize the Java objects. This uses the JSON format instead. It can be downloaded from the Maven Central Repository and does not have other dependencies. Let us have a look how this works –

Listing 13 - Implementing JSON IO based parser.

  package com.home.json.parse;
   
  import com.cedarsoftware.util.io.JsonObject;
  import com.cedarsoftware.util.io.JsonReader;
  import com.cedarsoftware.util.io.JsonWriter;
  import com.home.json.vo.ValueObject;
   
  public class JSONIOBasedParser {
   
      public JSONIOBasedParser() {
          ValueObject valObj = new ValueObject();
          valObj.setAge(34);
          valObj.setName("Aliah Gandhi");
          valObj.setMessage("You are required to be at the airport by 10:00 PM. "
                  + "You will meet a person called Olovia Campbell."
                  + "She will handover your tickets and other travel documents.");
          System.out.println("JSON STRING = " + toJSONObj(valObj));
   
          String JSON_STRING = "{\"age\":34,\"name\":\"Aliah Gandhi\",\"message\":\"You are required to be at the airport by 10:00 PM. You will meet a person called Olovia Campbell. She will handover your tickets and other travel documents.\"}";
   
          ValueObject valuObject = fromJSONObj(JSON_STRING);
          System.out.println("DATA FROM OBJECT ");
          System.out.println("AGE = " + valuObject.getAge() + " ");
          System.out.println("NAME = " + valuObject.getName() + " ");
          System.out.println("Message = " + valuObject.getMessage() + "");
      }
   
      private ValueObject fromJSONObj(String jSON_STRING) {
          ValueObject valuObject = new ValueObject();
          JsonObject object  = (JsonObject)JsonReader.jsonToJava(jSON_STRING);
          
          valuObject.setAge(Integer.parseInt((object.get("age")).toString()));
          valuObject.setName((object.get("name")).toString());
          valuObject.setMessage((object.get("message")).toString());
          return valuObject;
      }
   
      private String toJSONObj(ValueObject valObj) {
          String JSONStr = "";
          JSONStr = JsonWriter.objectToJson(valObj);
   
          return JSONStr;
      }
   
      public static void main(String[] args) {
         new JSONIOBasedParser();
      }
  }
  

Listing 14 - Output of the JSON IO based parser class.


<p>JSON STRING =
{"age":34,"name":"Aliah Gandhi","message":"You
are required to be at the airport by 10:00 PM. You will meet a person called
Olovia Campbell.She will hand over your tickets and other travel
documents."}</p>

<p>DATA FROM OBJECT </p>

<p>AGE = 34 NAME = Aliah
Gandhi </p>

<p>Message = You are
required to be at the airport by 10:00 PM. You will meet a person called Olovia
Campbell. She will handover your tickets and other travel documents.</p>

Conclusion

Through this document, I have tried and covered the various aspects of JSON data interchange format. Also I have talked about some major parsers which are commonly used in the Java based applications to parse a JSON. The parsers which I have talked are -

  • Jackson
  • GSON
  • JSON Lib
  • Flex JSON
  • JSON

There are other parsers also available which are equally competent to take on the job. I hope you will enjoy reading this article.


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login