Json in Java - Convert Json object to Java and Java object to Json

JSON so called 'JavaScript Object Notation' is a lightweight data exchange format, it is a subset of 'JavaScript programming language standard ECMA-262 '. JSON is a language independent data interchange format that is fully supported by java language.

In java there are a number of standards and techniques to deal with JSON, GSON given by Google is the most commonly and easiest way of JSON implementation in java . In today's discussion we will come to know 'How to convert a JSON object to Java' and 'How to convert a Java object to JSON'.

GSON Maven Dependency

To implement JSON in java using GSON we need to add an external Maven Dependency as shown below:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tb.java</groupId>
	<artifactId>SimpleJavaProject</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SimpleJavaProject</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.5</version>
		</dependency>

	</dependencies>
</project>


GSON provides two useful methods and everything moven around these two methods.
toJson() ? Convert Java object to JSON format
fromJson() ? Convert JSON into Java object

In this tutorial we will see step by step explanation and implementation of parse JSON in Java using Gson.


Project Structure

This is the overall project structure for today's discussion. We have added a 'gson' jar under lib folder to make our project to use gson capabilities. 'JavaToJson.java' file contains code for converting java object to json and 'JsonToJava.java' file contains code for convert json object to java. 'json' folder contains 'student.json' file that we will be using to read and convert json from. We have added a domain class 'Student.java' this will be used to carry an object to convert to json and from json. Please make sure you have added 'gson' jar to project's classpath.



Convert Java object to JSON using GSON

Convert java object to json is an easy task, all we need to do is having an java object and use a 'toJson' method from 'Gson' API.

src\com\beingjavaguys\domain\Student.java

This is a simple java domain class to obtain an object so that convert from java to json and json to java can be demonstrated.
package com.beingjavaguys.domain;  
  
import java.util.List;  
  
public class Student {  
   
 private int id;  
 private String firstName;  
 private String lastName;  
 private String gender;  
 private String city;  
 private List<String> interests;  
  
// getters and setters  
 public int getId() {  
  return id;  
 }  
 public void setId(int id) {  
  this.id = id;  
 }  
 public String getFirstName() {  
  return firstName;  
 }  
 public void setFirstName(String firstName) {  
  this.firstName = firstName;  
 }  
 public String getLastName() {  
  return lastName;  
 }  
 public void setLastName(String lastName) {  
  this.lastName = lastName;  
 }  
 public String getGender() {  
  return gender;  
 }  
 public void setGender(String gender) {  
  this.gender = gender;  
 }  
 public String getCity() {  
  return city;  
 }  
 public void setCity(String city) {  
  this.city = city;  
 }  
 public List<String> getInterests() {  
  return interests;  
 }  
 public void setInterests(List<String> interests) {  
  this.interests = interests;  
 }  
   
}  


src\com\beingjavaguys\core\JavaToJson.java

This is a simple java classes which contains actual code of convert java object to json, we have added some data to Student objcet here. All we did here is obtain an object from Gson and called toJson() method on our student object.
package com.beingjavaguys.core;  
  
import java.util.ArrayList;  
import com.beingjavaguys.domain.Student;  
import com.google.gson.Gson;  
  
public class JavaToJson {  
 public void convertJavaToJson(){  
    
  // simple object from student domain class  
  Student student = new Student();  
    
  // added some data to student's object  
  ArrayList<String> interests = new ArrayList<String>();  
  interests.add("friends");  
  interests.add("women");  
  interests.add("chatting");  
    
  student.setId(1);  
  student.setFirstName("ankush");  
  student.setLastName("thakur");  
  student.setGender("male");  
  student.setInterests(interests);  
    
  // obtained Gson object   
  Gson gson = new Gson();  
    
  // called toJson() method and passed student object as parameter  
  // print generated json to console  
  System.out.println(gson.toJson(student));  
    
  }  
}  

Output

This is generated json from student java object.
{"id":1,"firstName":"ankush","lastName":"thakur","gender":"male","city":"gurgaon","interests":["friends","women","chatting"]}


Convert JSON object to Java using GSON

Convert json object to java is an easy task all we need to do is having an json file and reading json from there to convert to java.

Objective JSON file to convert in Java object

This is sample json String written under 'student.json' file, we will read this in our code to convert into a java object.
{"id":1,"firstName":"ankush","lastName":"thakur","gender":"male","city":"gurgaon","interests":["friends","women","chatting"]}

src\com\beingjavaguys\core\JsonToJava.java

We have read json from student.json file and passes the stream to 'fromJson()' method. Than we have iterated the object simply to see how to use data contained in json.
package com.beingjavaguys.core;  
  
import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileReader;  
  
import com.beingjavaguys.domain.Student;  
import com.google.gson.Gson;  
  
public class JsonToJava {  
   
 public void jsonToJava(){  
    
  try {   
   // obtained a file object from json file  
   File file = new File("json/student.json");  
  
   // get json as buffer  
   BufferedReader br = new BufferedReader(new FileReader(file));  
  
   // obtained Gson object  
   Gson gson = new Gson();  
  
   // called fromJson() method and passed incoming buffer from json file  
   // passed student class reference to convert converted result as Student object  
   Student student = gson.fromJson(br, Student.class);  
     
   // printed student data on console  
   System.out.println("id: "+student.getId()+" First Name:"+student.getFirstName()  
   +" Last Name: "+student.getLastName()+" Gender: "+student.getGender()+" City: "+student.getCity());  
     
   System.out.println("Interests: ");  
   for(int i=0;i<=student.getInterests().size()-1;i++){  
    System.out.println(student.getInterests().get(i));  
   }  
     
  } catch (FileNotFoundException e) {  
   e.printStackTrace();  
  }  
    
    
 }  
}  

Output

This is a screenshot from console, we will get an output like this after conversion is done.


Implementation class code

src\com\beingjavaguys\core\JsonImplementation.java

This is nothing but a simple implementation class having main method, we have called our codes here to demonstrate actual conversion.
package com.beingjavaguys.core;  
  
public class JsonImplementation {  
 public static void main(String args[]){  
  
  // java to json conversion  
  JavaToJson javaToJson = new JavaToJson();  
  javaToJson.convertJavaToJson();  
    
  // json to java conversion  
  JsonToJava jsonToJava = new JsonToJava();  
  jsonToJava.jsonToJava();  
    
 }  
}


In this particular blog we learn how to parse json in java and came across 'How to convert json object to java using Gson' and 'how to convert java object to json using Gson'. In upcoming blogs we will come across more about json implementations in java and other useful stuff. Read more about XML & JSON under SAX & DOM & Xml parser in Java & JDOM2 & XML parser in Java JSON, and JAXB - Marshalling & Unmarshalling in Java categories.

Download complete project source code from: GitHub