TechAlpine – The Technology world

JSON data and Java – How it works?

JSON and Java

JSON and Java – How it works?

Overview:

JSON, which is the abbreviation of JavaScript Object Notation, is a text-based data exchange format that is used in web applications and for server responses. JSON happens to be a lot more compact and lighter when compared to XML. Besides, JSON objects are supported by numerous technologies and are also easy to write and read. So, it is undoubtedly used by a majority of developers these days and is equally popular in web services with Java.

In this article, we will take a look at different sections of JSON and how it can be used in Java programming.







What are the characteristics and uses of JSON?

JSON has three primary characteristics that make it suitable for use with Java. These also have a lot to do with the popularity of the format in the present times. These are –

  • Reading and writing JSON is very easy.
  • JSON is lightweight and makes use of a text-based exchangeable format.
  • It is independent of other languages and supported by a majority of them.

Coming to the use of JSON, there are quite a few of them that we shall look into. These are –

  • JSON is largely used for writing applications that are based on JavaScript.
  • The format is preferred for the serialization and transmission of structured data over any network.
  • The main use of JSON is to transmit data between web applications and web servers.
  • APIs and web services are known to make use of JSON format in order to provide public data.
  • JSON is supported by modern technologies and can be used with modern programming languages.

Java APIs for JSON processing

JSR 353 is the Java API that is used for JSON processing. It is known to offer portable APIs for generation, parsing, transformation and querying of JSON data by making use of object model and streaming of APIs.

Object Model API – The Object Model API is pretty much like the DOM Parser and is largely favourable for objects that are small. This model is known to create a treelike structure for the JSON data in the memory which can be randomly accessed. This tree-like structure can be queried and navigated. This model definitely proves to be flexible and allows for processing that makes it possible to randomly access the total contents of the tree. However, when it is compared to the streaming model, it falls short considering that it is not as efficient and also requires more memory.



Streaming API – Favourable for situations where you are dealing with a large memory and do not want to keep the whole object in the memory, the Streaming API is similar to the StaX Parser. It offers a way that allows for the parsing and generation of JSON in a streaming manner. The API is known to offer a parser that is event-based, which further allows the developer of the application to request the next event instead of having to handle the event in a callback. This is something that allows the coder to have more procedural control over the processing of JSON data. It allows the application code to either process or discards the parser event and then asks for the upcoming event. This streaming model is particularly useful where random access to different parts of data is not required but rather, local processing is needed. In a similar manner, the streaming API is also good for the generation of well-formed JSON data in a stream, writing an event at a time.

Third party Java APIs for JSON processing

Besides the Java API, there are also few third-party Java libraries that can be used for the processing of JSON data. We shall just take a look at three of them.

Jackson

Jackson is a very popular library based in Java and is used for the serialization and mapping of Java objects to JSON and vice-versa. Jackson has also proven to be a highly efficient API.

JSON.simple

Just as the name suggests, JSON.simple is a very simple JSON library for reading and writing of data.

Google Gson

Google Gson is a pretty popular third-party API that is used for numerous public projects these days. Initially, though, this API was created by Google for use inside the organization.

Environment setup

Please follow the steps below to set the environment ready to run the Java programs.

  • Down load JDK from the following link and set the class path

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Now your environment is ready to run the sample applications.








Sample applications

In this section we will check examples to write and read JSON data by using Java programs. Following is the project structure created in Eclipse IDE.

Eclipse project structure

Image1: Project structure in Eclipse

In the first example, we have created one json file in the local file system and write the data into it.

Listing 1: Writing JSON data in a file

package techalpine;

import java.io.FileWriter;

import java.io.IOException;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

public class JsonWriteDemo {

public static void main(String[] args) {

//Preparing JSON object

JSONObject jsonobj = new JSONObject();

jsonobj.put(“name”, “techalpine.com”);

jsonobj.put(“service”, “Learning”);

//Preparing message list

JSONArray msglist = new JSONArray();

msglist.add(“e-learning”);

msglist.add(“content learning”);

msglist.add(“video tutorial”);

jsonobj.put(“messages”, msglist);

try {

//Writing to a file

FileWriter filewrtr = new FileWriter(“jsonfile.json”);

filewrtr.write(jsonobj.toJSONString());

filewrtr.flush();

filewrtr.close();

} catch (IOException ex) {

ex.printStackTrace();

}

System.out.print(jsonobj);

}

}

Now run the program from command prompt or Eclipse IDE. The output will be displayed as shown below.

JSON output

Image 2: Showing output in a file

This is the second example, where we have taken the same json data file created in the first example. The JSON data is iterated and displayed as an output.








Listing 2: Reading JSON data from a file

package techalpine;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.Iterator;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;

public class JsonReadDemo {

@SuppressWarnings(“unchecked”)

public static void main(String[] args) {

JSONParser jsnprsr = new JSONParser();

try {

//Read from JSON file

Object fileobj = jsnprsr.parse(new FileReader(“jsonfile.json”));

//Create JSON object

JSONObject jsonObject = (JSONObject) fileobj;

String orgname = (String) jsonObject.get(“name”);

System.out.println(“Organization name: “+orgname);

String service = (String)jsonObject.get(“service”);

System.out.println(“Service name: “+service);

//Iterate through the message loop

JSONArray jsnmsg = (JSONArray) jsonObject.get(“messages”);

Iterator<String> jsniterate = jsnmsg.iterator();

System.out.println(“Messages :- “);

while (jsniterate.hasNext()) {

System.out.println(jsniterate.next());

}

} catch (FileNotFoundException ex) {

ex.printStackTrace();

} catch (IOException ex) {

ex.printStackTrace();

} catch (ParseException ex) {

ex.printStackTrace();

}

}

}

Now run the program from command prompt or Eclipse IDE. The output will be displayed as shown below.







JSON output

 

Image 3: Showing output resultConclusion:

Working with JSON data in Java can be fairly simple, considering the numerous APIs that are available for the task. Using these APIs, one can –

  • Parse input streams to immutable objects/event streams
  • Write immutable objects/event streams to output streams
  • Navigate immutable objects using programs
  • Using programs to build immutable objects.

The above article demonstrates the manner in which one can work with JSON data in Java. As for the choice of the API, one can stick to the Java API for JSON or even go with the third-party APIs that are available.


Please follow and like us:
0
Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *


5 × = 40

============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------

Enjoy this blog? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+
http://techalpine.com/json-data-and-java-how-it-works">
LinkedIn