

You must be logged to download. Click here to login




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




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

Working with JSON Data in Java

In this tutorial, we shall learn about how one can work with JSON data in Java. We shall first go through a little introduction, before looking at the programming aspects.

Communication between the user’s browser and the host server forms a key part of everything that happens on the Internet. In this regard, data interchange is one major aspect. On a similar note, JSON is meant for the interchange of human-readable data. While XML, Extensible Markup Language, also serves a similar purpose, it is said to be somewhat on the heavier side. In this respect, JSON has largely taken over and is largely used by developers across the world today.

What is JSON?

Coming to it again, JSON, expanded to JavaScript Object Notation, is a text-based open standard that is used for the interchange of human-readable data. These data are made up by objects that consist of attribute-value pairs.

Although JSON is derived from JavaScript, it can be used with several programming languages. These include the likes of Java, C, C++, Python, Ruby, Perl, etc.

Uses of JSON

JSON finds application in the following –

  • Writing application based on JavaScript, such as websites and browser extensions.
  • For the transmission and serialization of structured data.
  • Transmission of data between application and the server.
  • JSON data is used by APIs and web services for the public data.

Aspects of JSON

JSON has the following aspects –

  • Easy in terms of reading and writing.
  • It is lightweight and text-based.
  • Independent of any language.

JSON with Java

JSON is pretty popular, finding large usage in server response and web applications. This is mainly because it is lightweight and offers more compactness than XML.

JR535 is available in Java Enterprise Edition 7 and happens to be the API for JSON processing. The reference implementation is jsonp.

There are two methods that are offered by the JSON API for JSON processing. These are –

Object Model API – The Object Model API is almost like that of the DOM Parser and meant for small objects. The model creates a treelike structure for the JSON data in the memory. After this it can be accessed in a random manner. The structure can also be queried and navigated. T is deemed as flexible and the processing makes it possible to access the total contents of the structure. However, it is not as efficient as the streaming model and also needs more memory.

Streaming API – Good for situations where you are dealing with a large memory, the Streaming API is just like the StaX Parser. It is also ideal where you do not want to keep the whole object in the memory. The parsing and generation of JSON is possible in a streaming way. The control for parsing and generation is with the coder here.

The API offers an event-based parser. This permits a developer in requesting a successive event rather than handling that in a callback. This permits the developer to possess more procedural control over processing of JSON data. The streaming model is mainly useful for local processing when there is no need for random access to different parts of data. On a similar note, the streaming API is also good for generating streamed well-formed JSON data.

Useful interfaces in Java JSON API

There are a few important interfaces that we should know about.

  • javax,json,JsonReader – This is used for reading of JSON objects or reading arrays to JSON objects. It lies under Json class or the JsonRederFactory.
  • javax,json,JsonWriter – This serves the purpose of writing JSON objects to the output stream.
  • javax.json.stream.JsonParser – This is known to function as a pull parser. It also provides streaming support for the reading of JSON objects.
  • javax.json.stream.JsonGenerator – This is meant for writing JSON objects to output source in a streamable way.
  • javax.json.Json – This serves as a factory class and JSON processing objects can be created from it. It houses the common classes used for creation of these objects, along with their factories. The factory classes further have all the ways for the creation of these objects.
  • javax.json.JsonObjectThis basically represents a JSON object that is immutable.

Usage of JSON in Java

We shall now take a look into the usage of Java JSON API with a rather simple example.

Listing 1. Employ.txt

       "name":"Sonal Kumar",
                    "street":"El Paso Road",
       "phnumbers":[9456644228, 8675678902],

Here are the Java bean classes that represent the given JSON format.

Listing 2. Java Beans classes

package sample.model;
import java.util.Arrays;
public class Employee {
       private int iden;
       private String name;
       private boolean perma;
       private Address address;
       private long[] phnnumbers;
       private String role;
       public int getid() {
             return iden;
       public void setid(int iden) {
             this.iden = iden;
       public String getname() {
             return name;
       public void setname(String name) {
             this.name = name;
       public boolean isperma() {
             return perma;
       public void setperma(boolean perma) {
             this.perma = perma;
       public Address getaddress() {
             return address;
       public void setaddress(Address address) {
             this.address = address;
       public long[] getphnnumbers() {
             return phnnumbers;
       public void set phnnumbers(long[] phnnumbers) {
             this. phnnumbers = phnnumbers;
       public String getrole() {
             return role;
       public void setrole(String role) {
             this.role = role;
       public String toString(){
             StringBuilder stb = new StringBuilder();
             stb.append("##### Employee Details #####\n");
             stb.append("Phone Numbers="+Arrays.toString(getphnnumbers())+"\n");
             return stb.toString();

Listing 3. Java Beans for the address

package sample.model;
public class Address {     
       private String strt;
       private String city;
       private int zip;    
       public String getstreet() {
             return strt;
       public void setstreet(String street) {
             this. strt = strt;
       public String getcity() {
             return city;
       public void setcity(String city) {
             this.city = city;
       public int getzip() {
             return zip;
       public void setzip (int zip) {
             this.zip = zip;
       public String toString(){
             return getstreet() + ", "+getcity()+", "+getzip();

The toString() method has been overridden here so that it returns human-readable form for use in JSON implementation classes.

Java JSON Read

Listing 4. Example of Java JSON read

package sample.json;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import sample.model.Address;
import sample.model.Employee;
public class EmployeeJSONReader {
       public static final String JSONFILE="employ.txt";     
             InputStream fin = new FileInputStream(JSONFILE);            
             //creation of JsonReader object
             JsonReader jsonReader = Json.createReader(fin);             
              * We can also make use of Factory,
             JsonReaderFactory factor = Json.createReaderFactory(null);
             jsonReader = factor.createReader(fin);
             for the creation of create JsonReader.
             //get JsonObject from JsonReader
             JsonObject jsonObject = jsonRead.readObject();        
             //we can close IO resource and JsonRead now
             //Retrieval of the data from JsonObj and creation of Employee bean
             Employee employ = new Employee();       
             //reading of the arrays from json
             JsonArray jsonarray = jsonObject.getJsonArray("phnnumbers");
             long[] phnnumbers = new long[jsonarray.size()];
             int indx = 0;
             for(JsonValue value : jsonarray){
                    phnnumbers[indx++] = Long.parseLong(value.toString());
             //reading the inner object from the json object
             JsonObject innerJsonObj = jsonObj.getJsonObject("address");
             Address address = new Address();
             //printing of the employee bean information

You can see that the implementation here is rather simple and on execution of this code, you will get the result as given below.

##### Employee Details #####
Name=Sonal Kumar
Phone Numbers=[9456644228, 8675678902]
Address=El Paso Road, California, 920134

Java JSON Write

Listing 5. Example of Java JSON write

package sample.json;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import sample.model.Address;
import sample.model.Employee;
public class EmployeeJSONWriter {
             Employee employ = createEmployee();
             JsonObjectBuilder empbuilder = Json.createObjectBuilder();
             JsonObjectBuilder addressbuilder = Json.createObjectBuilder();
             JsonArrayBuilder phonenumbuilder = Json.createArrayBuilder();
             for (long phone : employ.getphnnumbers()) {
             addressbuilder.add("street", employ.getaddress().getstreet())
                                        .add("city", employ.getaddress().getcity())
                                               .add("zip", employ.getaddress().getzip());            
             empbuilder.add("id", employ.getid())
                                  .add("name", employ.getname())
                                        .add("permanent", employ.isperma())
                                               .add("role", employ.getrole());
             empbuilder.add("phnnumbers", phoneNumBuilder);
             empbuilder.add("address", addressbuilder);            
              JsonObject empJsonObject = empbuilder.build();        
             System.out.println("Employee JSON String\n"+empJsonObject);        
             //writing to the file
             OutputStream ots = new FileOutputStream("emp.txt");
             JsonWriter jsonWriter = Json.createWriter(ots);
              * We can also get JsonWriter, 
             JsonWriterFactory factory = Json.createWriterFactory(null);
             jsonWriter = factory.createWriter(ots);
             from JsonWriterFactory.
       public static Employee createEmployee() {
             Employee employ = new Employee();
             emp.setphnnumbers(new long[] { 9876543, 13579});
             Address add = new Address();
             add.setstreet("Jessore Road");
             return employ;

On running the above given code, you will get the following output as is given below.

Employee JSON String
{"id":1567,"name":"Steven","permanent":false,"role":"CEO","phnnumbers":[9876543,13579],"address":{"street":"Jessore Road","city":"Kolkata","zipcode":700057}}

It is also worthy to note that JSON object gets stored in the emp.txt file. The JsonObjectBuilder implements the builder pattern which further makes the data easy to use.


We took a look at some of the background involving the use of JSON and then about how it works with Java. Primarily, we learnt about the implementation in reading and writing aspects. While this is just a very basic tutorial to get you started, you can go on and build up from here.


What did you think of this post?

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




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

Click here to login