Convert JSON String to POJO Class Object in Java

  • Last updated Apr 25, 2024

In this tutorial, we will explore two different methods to convert a JSON String into a Java POJO Class object:

  1. Using ObjectMapper
  2. Using Gson Library
Using ObjectMapper

To make use of the ObjectMapper class, you have to add the jackson-databind dependency to your project.

ObjectMapper class 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 readValue() method of the ObjectMapper object.
  3. Pass the JSON String and the target class as parameters to the readValue() method. It automatically maps the JSON attributes to the corresponding fields in the POJO class.
  4. The method will return the corresponding target POJO class object representation of the JSON String.

Here's an example to demonstrate this:

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

// Converting from JSON string to Class object
Target target = objectMapper.readValue(jsonString, Target.class);

Let's look at an example JSON string that we want to change into a POJO Class object:

"{\"id\":1,\"firstName\":\"Danny\",\"lastName\":\"Brown\",\"active\":true}"

To change the JSON string data mentioned above into a Java POJO Class object, you need to create a Java POJO class with fields that have the exact same names as the JSON key names:

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 is an example code that demonstrates how to convert the JSON String into a Java POJO class object named User:

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

public class Example {

   public static void main(String[] args) {
      // Sample json string data
      String jsonString = "{\"id\":1,\"firstName\":\"Danny\", \"lastName\":\"Brown\", \"active\":true}";

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

      try {
	    // Converting from JSON string to Class object
	    User user = objectMapper.readValue(jsonString, User.class);

	   // Printing output
	   System.out.println("Id = " + user.getId());
	   System.out.println("First name = " + user.getFirstName());
	   System.out.println("Last name = " + user.getLastName());
	   System.out.println("Active = " + user.isActive());

      } catch (JsonMappingException e) {
	   e.printStackTrace();
      } catch (JsonProcessingException e) {
	   e.printStackTrace();
      }

   }

}
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 fromJson() method.
  9. Pass the JSON String and the  target class to the fromJson() method.

Here's an example to demonstrate this:

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

// Converting from json string to User class object
User user = gson.fromJson(jsonString, User.class);