Convert POJO Class Object to JSON String in Java
In this tutorial, we will show you two different ways for converting POJO Class object to JSON string in Java:
Using ObjectMapper
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.
To use ObjectMapper class, you need to install jackson-databind dependency to your project.
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.
Let the POJO Class that we need to convert to a JSON string be as follows:
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;
}
}
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
- Add Gson dependency to your project.
- You can create an object of Gson and use toJson() method to convert POJO Class object to JSON String as shown in the example below:
import com.google.gson.Gson;
public class Example {
public static void main(String[] args) {
//creating pojo class object with data
User user = new User();
user.setId(1);
user.setFirstName("Danny");
user.setLastName("Brown");
user.setActive(true);
// creating an object of Gson
Gson gson = new Gson();
// converting from pojo class object to json string
String jsonStringData = gson.toJson(user);
// printing output
System.out.println("User = " + jsonStringData);
}
}