Convert POJO Class Object to JSON String in Java

  • Last updated Apr 25, 2024

In this tutorial, you will learn how to convert a POJO class object to a JSON string in Java. We will explore two different techniques to serialize a Java object into its JSON representation:

  1. Using ObjectMapper
  2. Using Gson Library

Using ObjectMapper

To use ObjectMapper class, you need to install jackson-databind dependency to your project.

ObjectMapper provides methods for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.

In a Spring Boot project, the jackson-databind dependency is by default included in spring-boot-starter-web starter library. The Jackson version included that comes with Spring Boot starter library allows you to write read/write JSON data. However, it is a good practice to specify this dependency because Spring update could change the functionality.

To convert a POJO class object to a JSON string using ObjectMapper in Java, we can do the following:

  1. First, create an instance of the ObjectMapper class.
  2. Then, use the writeValueAsString() method of the ObjectMapper object.
  3. Pass the POJO class object as a parameter to the writeValueAsString() method.
  4. The method will return the corresponding JSON string representation of the POJO object.

Here's an example to demonstrate this:

// Creating an instance of the ObjectMapper class
ObjectMapper objectMapper = new ObjectMapper();

// Converting POJO class object to JSON string
String jsonString = objectMapper.writeValueAsString(pojoObject);


Consider the following example where User is the POJO Class that we want to convert into a JSON string:

public class User {
   private int id;
   private String firstName;
   private String lastName;
   private boolean active;

   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 boolean isActive() {
      return active;
   }

   public void setActive(boolean active) {
      this.active = active;
   }

}

Here's an example code that shows how you can convert the above POJO class called User to JSON String in Java:

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

public class Example {

   public static void main(String[] args) {
	User user = new User();
	user.setId(1);
	user.setFirstName("Danny");
	user.setLastName("Brown");
	user.setActive(true);

	// creating an object of ObjectMapper class
	ObjectMapper objectMapper = new ObjectMapper();

	// converting from pojo class object to json string
	String jsonString = "";
	try {
	     jsonString = objectMapper.writeValueAsString(user);
	} catch (JsonProcessingException e) {
	     e.printStackTrace();
	}
	System.out.println("User = " + jsonString);
   }

}


Using Gson Library

The Gson library is a popular Java library developed by Google that provides functionality for converting Java objects to JSON (serialization) and JSON to Java objects (deserialization). It makes working with JSON data in Java applications much easier and more convenient.

To convert a POJO class object to a JSON string using Gson library in Java, do the following:

  1. If you are using Maven, add the following dependency to your project's pom.xml file:

  2. <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>
  3. If you are using Gradle, add the following dependency to your project's build.gradle file:

  4. implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'
  5. Import the necessary classes.

  6. import com.google.gson.Gson;

  7. Create an instance of the Gson class.
  8. To convert a Java object to a JSON string, use the toJson() method.

Here's an example to demonstrate this:

// Create an instance of the Gson class
Gson gson = new Gson();

// converting a Java object to a JSON string
String jsonStringData = gson.toJson(userObject);