You are here
Home > java >

How to work with JSON in Java?

How to work with JSON in Java?Almost every Java developer come across the word ‘JSON’ during project development. In fact, not only the Java developer, but also other language developers, even UI developers. Almost everyone in the software industry directly or indirectly, sooner or later get a chance to work with JSON. Now you can imagine how important it is to know in & out of it. You may have a question in your mind ‘How to work with JSON in Java?’.

Although its syntax is very easy to write, but sometimes it creates confusion when an object is a bit complex. You must require knowledge of it when you test your application by sending or receiving JSON data. Moreover, it also becomes important while resolving the data format error. In this article, we will do enough practice with clear & concise concepts to become expert in handling any format of JSON data. Let’s get into our topic ‘How to work with JSON in Java?’.

What will you learn from this article ?

After going through the complete article you will learn about :

1) What is JSON and how to represent it?
2) Where do we use the JSON & Why ?
3) How to represent JSON in case of Java Objects like in List, Set, Map, Properties, Arrays etc.?
4) Additionally How to represent a complex Java object as JSON String ?
5) How to test REST applications when passing JSON string and getting Java Objects and vice versa?
6) Then, How to convert Java Objects into JSON and JSON into Java Objects programmatically ?
7) As a Java developer that’s enough to answer ‘How to work with JSON in Java?’

What is JSON ?

JSON is a lightweight data syntax of storing, transferring & exchanging data. It stands for JavaScript Object Notation. Its relationship to JavaScript is that it shares its syntax (more or less) with a subset of JavaScript literals. A JSON object contains data in the form of key-value pair just like Properties file or Map in Java but has different syntax. One pair of key and value is called an entry. Each entry is separated by comma. The key must be quoted(” “), value is quoted only if type is String. For example:

{ "id" : 10, "name": "Mary", "salary" : 3775.6 } 
♦ One { } (curly brace) indicates one Object.

Suppose we have a class Employee as below

Employee.java
public class Employee {
	
	Integer eId;
	String eName;
	Double eSal;
	
	public Employee(Integer eId, String eName, Double eSal) {
		this.eId = eId;
		this.eName = eName;
		this.eSal = eSal;
	}
}
Java Object to JSON Conversion
If we create an object of Employee as below:

Employee e = new Employee(137229,"Robert",80755.0);


Above data can be written in JSON as below:

{ "eId": 137229, "eName": "Robert", "eSal":80755.0 }

If you need more information on JSON, kindly visit json website.

What is JSON format?

JSON comes with a conventional text-based format for representing structured data. It is similar to the JavaScript object syntax. Commonly we use it for transmitting data in web applications from server to client and vice versa. It has a nominal number of value types such as strings, numbers, Booleans, lists, objects, and null. Although these types are available in all common programming languages which makes JSON a good contestant to transmit data across all languages.

Where is JSON representation used?

JSON will be used in places where we need small data storage, data transfer & data exchange. However, we, as a java developer use it in Webservices most of the times. It is the most popular format of data used in REST webservices. Even Spring Boot REST API supports JSON format by default. Moreover, if you want to use xml format, you will have to provide additional configurations while working with Spring Boot REST. JSON is lightweight and universally accepted format to store, transfer & exchange data. Even Mongo DB stores data in the form of JSON. So it is very important to clear your concepts of JSON before working with Mongo DB as well.

Sometimes one application interacts with another application irrespective of the programming/scripting languages they are written in. In this case, we need a common format of data to establish communication between them so that each application can understand it easily. JSON becomes the best choice in this scenario as it is language-independent. Needless to say that this type of communication generally happens in webservices concept.

How to represent List/Set/Array of Java as a JSON ?

JSON stores List, Set & Array Objects of Java as an Array only.
JSON Syntax will be as below (variable name as a key and values within [ ] separated by comma). For example:

"key": [ val1, val2, val3, val4....... ]

Note : You are advised to use at least JDK 9 to execute examples of this article, or modify your code accordingly. We will use of() method in order to initialize the collections in many places that was introduced in JDK 9.

For example, let’s consider a class Student as below :

Student.java
class Student {
	
	  Integer id;
	  Set<String> subjects;
	  List<Integer> marks;
	  String[] grades;
	
	  public Student(Integer id, Set<String> subjects, List<Integer> marks, String[] grades) {
		this.id = id;
		this.subjects = subjects;
		this.marks = marks;
		this.grades = grades;
	}
}
Java Object vs JSON
Java Object Representation:

Student s = new Student(
		500, 
        Set.of("Physics","Chemistry","Mathematics"),
	    List.of(84,65,90),
	    new String[]{"B","C","A"}
	    );

JSON Representation:

 {
   "sid"      : 500,
   "subjects" : [ "Physics","Chemistry","Mathematics" ],
   "marks"    : [ 84,65,90 ],
   "grades"   : ["B","C","A" ]
 }

How to represent Map/Properties of Java as a JSON ?

JSON stores Map, Properties of Java as an Object only (i.e. Within the curly brace {} with key-value pair).

For example, consider below Student class with a Map variable.

Student.java
class Student {
	
	Integer id;
	Map<String,Integer> marks;
	
	public Student(Integer id, Map<String, Integer> marks) {
		this.id = id;
		this.marks = marks;
	}
}
Java Object vs JSON
Java Object Representation:

Student s = new Student(346, Map.of("Physics",84,"Chemistry",65,"Mathematics",90));

JSON Format Representation:

{
  "sid"   : 346,
  "marks" : {
           "Physics" : 84,
	       "Chemistry" : 65,
	       "Mathematics" : 90
          }

}  

How to represent JSON if Java class has a ‘HAS-A’ relationship(Association Mapping)?

However, JSON stores objects as a ‘HAS-A’ relationship like one object containing another object. For example, consider we have One Student class with Address class as ‘HAS-A’ variable as below.

Student.java & Address.java
class Student {
	
	Integer id;
	Map<String,Integer> marks;
	Address address;
	
	public Student(Integer id, Map<String, Integer> marks, Address address) {
		this.id = id;
		this.marks = marks;
		this.address = address;
	}
}

class Address {
	
	Integer houseNo;
	String streetName;
	String countryName;
	
	public Address(Integer houseNo, String streetName, String countryName) {
		this.houseNo = houseNo;
		this.streetName = streetName;
		this.countryName = countryName;
	}
}
Java Object Vs JSON
Java Object Representation:

Student s = new Student(346,
						Map.of("Physics",84,"Chemistry",65,"Mathematics",90),
					    new Address(124, "Main Street", "Canada")
					   );

JSON Format Representation:

{
  "sid"   : 346,
  "marks" : {
           "Physics"     : 84,
	       "Chemistry"   : 65,
	       "Mathematics" : 90
            }
"address" : { 
			"houseNo"      : 124,
			"sreetName"    : "Main Street",
			"countryName"  : "Canada"
			}

}  

How to represent a Complex JSON data?

If you are clear with all above explained JSON data representations as of now, You can easily create JSON representation of a complex structure of data. Let’s create a complex JSON representation. Let’s assume that we have a student class with three variables Integer, Map & a List of Object Address. Address class has 4 variables in which 3 are primitives and one variable with ‘HAS-A’ relationship called House. House class again has 3 primitive variables. For example, observe the below code:

Student.java, Address.java, House.java
public class Student {
	
	Integer id;
	Map<String,Integer> marks;
	List<Address> addresses;
	
	public Student(Integer id, Map<String, Integer> marks, List<Address> addresses) {
		this.id = id;
		this.marks = marks;
		this.addresses = addresses;
	}
}

class Address {
	
	String addrType;
	Integer houseNo;
	String streetName;
	String countryName;
	House house;
	
	public Address(String addrType, Integer houseNo, String streetName, String countryName, House house) {
		this.addrType = addrType;
		this.houseNo = houseNo;
		this.streetName = streetName;
		this.countryName = countryName;
		this.house = house;
	}	
}

class House {
	
	Integer noOfRooms;
	String houseType;
	Integer noOfWindows;
	
	public House(Integer noOfRooms, String houseType, Integer noOfWindows) {
		this.noOfRooms = noOfRooms;
		this.houseType = houseType;
		this.noOfWindows = noOfWindows;
	}
}
Java Objects vs JSON
Java Object Representation:

Student s = new Student(
				346,
				Map.of("Physics",84,
					   "Chemistry",65,
					   "Mathematics",90),
				List.of(new Address("Present Address",
									124, 
									"Main Street",
									"Canada",
									new House(3,"Flat",2) 
								   ),
						new Address("Permanent Address",
									344, 
									"Loyal Street", 
									"United Kingdom",
									new House(5,"Row House",3)
								   )
						)
				);

JSON Format Representation:

{
  "sid"   : 346,
  "marks" : {
           "Physics"     : 84,
	       "Chemistry"   : 65,
	       "Mathematics" : 90
            }
"addresses" :[ 
              { 
				"addrType"     : "Present Address",
			    "houseNo"      : 124,
			    "sreetName"    : "Main Street",
			    "countryName"  : "Canada",
				"house"        : { 
                                   "noOfRooms"   : 3, 
					               "houseType"   : "Flat", 
								   "noOfWindows" : 2
								 }
			  },
			  { 
				"addrType"     : "Permanent Address",
			    "houseNo"      : 344,
			    "sreetName"    : "Loyal Street",
			    "countryName"  : "United Kingdom",
				"house"        : { 
                                   "noOfRooms"   : 5, 
								   "houseType"   : "Row House",
								   "noOfWindows" : 3
                                 }
			  }
            ]
}  

How to convert Java Objects into JSON and JSON into Java Objects programmatically?

In order to convert  java object from JSON & vice versa, there are two APIs
1. Jackson API
2. GSON API
Here we will use the popular Jackson API. It provides ObjectMapper class to do conversions. In order to perform the conversions, we will use below methods.

writeValueAsString() : converts java object into JSON
readValue() : converts JSON into java Object

Note on Required jars : If you are using Spring Boot Web Project, no dependency needs to be added. In other cases, you will need to add Jackson jars in your class path. For example, we have two classes in below code snippet : JSONUtil.java and one Person.java to test the results. You can use conversion methods of JSONUtil.java accordingly in your project as Utility methods.

Person.java

public class Person {

      String name;
      Integer age;
      String profession;

      public String getName() {
         return name;
      }
      public void setName(String name) {
         this.name = name;
      }
      public Integer getAge() {
         return age;
      }
      public void setAge(Integer age) {
         this.age = age;
      }
      public String getProfession() {
         return profession;
      }
      public void setProfession(String profession) {
         this.profession = profession;
      }

      @Override
      public String toString() {
         return "Person [name=" + name + ", age=" + age + ", profession=" + profession + "]";
      }
}

JSONUtil.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtil {

      private static ObjectMapper mapper;

      static {
         mapper= new ObjectMapper();
      }

      public static String convertJavaToJson(Object obj) {
         String resultAsJSON= "";
         try {
             resultAsJSON= mapper.writeValueAsString(obj);
         } catch (JsonProcessingException e) {
             e.printStackTrace();
         }
         return resultAsJSON;
      }

      public static <T> T convertJsonToJava(String jsonString, Class<T> cls) {
         T resultAsJavaObject = null;
         try {
             resultAsJavaObject= mapper.readValue(jsonString, cls);
         } catch (JsonProcessingException e) {
             e.printStackTrace();
         }
         return resultAsJavaObject;
      }

      public static void main(String[] args) {
         
         // Person Object As JSON
         Person p1 = new Person();
         p1.setName("Albert");
         p1.setAge(38);
         p1.setProfession("DBA");
         String personAsJSON= convertJavaToJson(p1);
         System.out.println("Person Object As JSON : " +personAsJSON);

         //JSON as Person Object
         Person p2= convertJsonToJava(personAsJSON,Person.class);
         System.out.println("JSON as Person Object : " +p2);
      }
}

Output

Person Object As JSON : {"name":"Albert","age":38,"profession":"DBA"}
JSON as Person Object : Person [name=Albert, age=38, profession=DBA]

Summary

After going through all the theoretical & example part of ‘How to work with JSON in Java?’, finally, we should be able to work with JSON in Java. Similarly, we expect from you to further extend these examples and implement them in your real project accordingly. Moreover, please feel free to provide your comments in the comments section below.

Further, if you want to go through other articles on latest concepts of Java published by us, kindly visit the blogs page.

close

7 thoughts on “How to work with JSON in Java?

  1. We have already Restcontroller that converts entity class as a json response then could clarify in which situation we can use jakson api

    1. @Pratap : Jakson API has been illustrated here just to provide information that what code Spring Boot framework uses internally. Sometimes we come across a situation when we don’t use annotations. In that situation it becomes useful to know the internal details.

Leave a Reply

Top