Map JSON String to POJO objects and POJO objects to JSON String in Java using Gson and Jackson

Introduction

This tutorial will show you how we can map JSON string to a list of POJO objects and a list of POJO objects to JSON string using Google API’s Gson as well as Jackson API’s ObjectMapper.

We will create nested POJO objects from JSON string or JSON string to nested POJO objects using both Gson and Jackson API.

Google Gson has the following features:

  1. Provudes simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  2. Allows pre-existing unmodifiable objects to be converted to and from JSON
  3. Has extensive support of Java Generics
  4. Allows custom representations for objects
  5. Supports arbitrarily complex objects with deep inheritance hierarchies and extensive use of generic types

Jackson has the following features:

  1. Streaming API or incremental parsing/generation: reads and writes JSON content as discrete events
  2. Tree model: provides a mutable in-memory tree representation of a JSON document
  3. Data binding: converts JSON to and from POJO’s
  4. Some comparison blogs click here blogs1, blog2

Google Gson performs faster than Jackson irrespective of small or large objects.

Prerequisites

Eclipse 2019-12, Java 1.8 or later, Maven 3.6.3 or Gradle 6.4.1, Gson 2.8.6, Jackson 2.11.1

Project Setup

Create a gradle or maven based project in Eclipse. The name of the project is java-json-object-or-object-json.

If you are creating gradle based project then use below build.gradle script:

plugins {
    id 'java-library'
}

repositories {
    jcenter()
}

dependencies {
    implementation('com.google.code.gson:gson:2.8.6')
    implementation('com.fasterxml.jackson.core:jackson-databind:2.11.1')
}

We are using both Gson and Jackson in the build file to show you conversion examples using Gson and Jackson.

If you are creating maven based project then use below pom.xml file:

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>com.roytuts</groupId>
	<artifactId>java-json-object-or-object-json</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>at least 1.8</java.version>
	</properties>
	
	<dependencies>		
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.8.6</version>
		</dependency>
		
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.1</version>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
                <configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

POJO Classes

POJO classes are required to convert from JSON string to Java object. We are creating nested POJO classes.

So A department may have multiple employees.

package com.roytuts.java.json.object.or.object.json;

public class Employee {

	private int id;
	private String name;
	private String email;

	public Employee() {
	}

	public Employee(int id, String name, String email) {
		this.id = id;
		this.name = name;
		this.email = email;
	}

	//getters and setters

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", email=" + email + "]";
	}

}
package com.roytuts.java.json.object.or.object.json;

import java.util.List;

public class Department {

	private int id;
	private String name;

	private List<Employee> employees;

	//getters and setters

	@Override
	public String toString() {
		return "Department [id=" + id + ", name=" + name + ", employees=" + employees + "]";
	}

}

JSON to Java Object using Gson

Now we will convert a JSON string to Java object using the following piece of code.

package com.roytuts.java.json.object.or.object.json;

import com.google.gson.Gson;

public class JsonToObjectUsingGoogleGson {

	public static void main(String[] args) {
		String json = "{\"id\":1, \"employees\":[{\"id\":1001,\"name\":\"Sumit\",\"email\":\"[email protected]\"}, {\"id\":1002,\"name\":\"Soumitra\",\"email\":\"[email protected]\"}, {\"id\":1003,\"name\":\"Gourab\",\"email\":\"[email protected]\"}, {\"id\":1004,\"name\":\"Debina\",\"email\":\"[email protected]\"}, {\"id\":1005,\"name\":\"Debabrata\",\"email\":\"[email protected]\"}, {\"id\":1006,\"name\":\"Liton\",\"email\":\"[email protected]\"}, {\"id\":1007,\"name\":\"Souvik\",\"email\":\"[email protected]\"}]}";

		Gson gson = new Gson();

		Department department = gson.fromJson(json, Department.class);

		System.out.println(department);
	}
}

Running the above example you will the following output:

Department [id=1, name=null, employees=[Employee [id=1001, name=Sumit, [email protected]], Employee [id=1002, name=Soumitra, [email protected]], Employee [id=1003, name=Gourab, [email protected]], Employee [id=1004, name=Debina, [email protected]], Employee [id=1005, name=Debabrata, [email protected]], Employee [id=1006, name=Liton, [email protected]], Employee [id=1007, name=Souvik, [email protected]]]]

Java Object to JSOn using Gson

Next we will convert Java object to JSON string using the following code.

Here I am not creating Employee or Department objects, rather I am first converting the JSON string to POJO then back to JSON.

package com.roytuts.java.json.object.or.object.json;

import com.google.gson.Gson;

public class ObjectToJsonUsingGoogleGson {

	public static void main(String[] args) {
		String json = "{\"id\":1, \"employees\":[{\"id\":1001,\"name\":\"Sumit\",\"email\":\"[email protected]\"}, {\"id\":1002,\"name\":\"Soumitra\",\"email\":\"[email protected]\"}, {\"id\":1003,\"name\":\"Gourab\",\"email\":\"[email protected]\"}, {\"id\":1004,\"name\":\"Debina\",\"email\":\"[email protected]\"}, {\"id\":1005,\"name\":\"Debabrata\",\"email\":\"[email protected]\"}, {\"id\":1006,\"name\":\"Liton\",\"email\":\"[email protected]\"}, {\"id\":1007,\"name\":\"Souvik\",\"email\":\"souvik.san[email protected]\"}]}";

		Gson gson = new Gson();

		Department department = gson.fromJson(json, Department.class);

		String outputJson = gson.toJson(department);

		System.out.println(outputJson);
	}

}

Running the above code you will get the following output:

{"id":1,"employees":[{"id":1001,"name":"Sumit","email":"[email protected]"},{"id":1002,"name":"Soumitra","email":"[email protected]"},{"id":1003,"name":"Gourab","email":"[email protected]"},{"id":1004,"name":"Debina","email":"[email protected]"},{"id":1005,"name":"Debabrata","email":"[email protected]"},{"id":1006,"name":"Liton","email":"[email protected]"},{"id":1007,"name":"Souvik","email":"[email protected]"}]}

JSON to Java Object using Jackson

We have seen how to convert JSOn to Java object using Google gson, now we will do the similar thing using Jackson API.

package com.roytuts.java.json.object.or.object.json;

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

public class JsonToObjectUsingJackson {

	public static void main(String[] args) {
		String json = "{\"id\":1, \"employees\":[{\"id\":1001,\"name\":\"Sumit\",\"email\":\"[email protected]\"}, {\"id\":1002,\"name\":\"Soumitra\",\"email\":\"[email protected]\"}, {\"id\":1003,\"name\":\"Gourab\",\"email\":\"[email protected]\"}, {\"id\":1004,\"name\":\"Debina\",\"email\":\"[email protected]\"}, {\"id\":1005,\"name\":\"Debabrata\",\"email\":\"[email protected]\"}, {\"id\":1006,\"name\":\"Liton\",\"email\":\"[email protected]\"}, {\"id\":1007,\"name\":\"Souvik\",\"email\":\"[email protected]\"}]}";

		ObjectMapper mapper = new ObjectMapper();

		Department department = null;
		try {
			department = mapper.readValue(json, Department.class);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println(department);
	}
}

Running the above code you will see the following output:

Department [id=1, name=null, employees=[Employee [id=1001, name=Sumit, [email protected]], Employee [id=1002, name=Soumitra, [email protected]], Employee [id=1003, name=Gourab, [email protected]], Employee [id=1004, name=Debina, [email protected]], Employee [id=1005, name=Debabrata, [email protected]], Employee [id=1006, name=Liton, [email protected]], Employee [id=1007, name=Souvik, [email protected]]]]

Java Object to JSON using Jackson

Now again we will convert java object to JSON string using Jackson API as we did using Google Gson API.

package com.roytuts.java.json.object.or.object.json;

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

public class ObjectToJsonUsingJackson {

	public static void main(String[] args) {
		String json = "{\"id\":1, \"employees\":[{\"id\":1001,\"name\":\"Sumit\",\"email\":\"[email protected]\"}, {\"id\":1002,\"name\":\"Soumitra\",\"email\":\"[email protected]\"}, {\"id\":1003,\"name\":\"Gourab\",\"email\":\"[email protected]\"}, {\"id\":1004,\"name\":\"Debina\",\"email\":\"[email protected]\"}, {\"id\":1005,\"name\":\"Debabrata\",\"email\":\"[email protected]\"}, {\"id\":1006,\"name\":\"Liton\",\"email\":\"[email protected]\"}, {\"id\":1007,\"name\":\"Souvik\",\"email\":\"[email protected]\"}]}";

		ObjectMapper mapper = new ObjectMapper();

		String outputJson = null;
		try {
			Department department = mapper.readValue(json, Department.class);
			outputJson = mapper.writeValueAsString(department);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println(outputJson);
	}

}

Running the above code you will see the following output:

{"id":1,"name":null,"employees":[{"id":1001,"name":"Sumit","email":"[email protected]"},{"id":1002,"name":"Soumitra","email":"[email protected]"},{"id":1003,"name":"Gourab","email":"[email protected]"},{"id":1004,"name":"Debina","email":"[email protected]"},{"id":1005,"name":"Debabrata","email":"[email protected]"},{"id":1006,"name":"Liton","email":"[email protected]"},{"id":1007,"name":"Souvik","email":"[email protected]"}]}

That’s all about conversion of JSON to Java and Java to JSON using Google Gson and Jackson APIs.

Source Code

Download

Thanks for reading.

Related posts

Leave a Comment