Class ObjectMapper
This is the most powerful class provided by Jackson API and maximum time we will use this class. ObjectMapper class is useful to create JSON object, JSON Array, converting a Java object to a JSON object and vice versa. In this post, we will use the ObjectMapper class to convert a Java Object to a JSON object.
JSON String
{
"firstName" : "Amod",
"lastName" : "Mahajan",
"gender" : "M",
"age" : 29,
"salary" : 10987.77,
"married" : false
}
We need to parse above JSON string to Java Object. To create a Java object we need a class i.e. one or multiple POJO classes based on the requirement. Let’s create a class with field name exactly (case sensitive) the same as node names in above JSON string because with default setting while parsing JSON object o Java object, it will look on getter setter methods of field names. In fact, access specifiers do not matter here. We will cover some interesting facts on it later.
package SerializationDeserialization;
public class Employee {
private String firstName;
private String lastName;
private String gender;
private int age;
private double salary;
private boolean married;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public boolean getMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
JSON Sring to POJO
Yup! ObjectMapper class provides various overloaded readValue() methods for different purposes. Reading JSON from a file or as a string which you will see mostly. This method will match fields of JSON string to passed POJO class fields and set values using setter methods which we can easily retrieve using getter methods.
package SerializationDeserialization;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializeJsonToJava {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String jsonString = "{\r\n" +
" \"firstName\" : \"Amod\",\r\n" +
" \"lastName\" : \"Mahajan\",\r\n" +
" \"gender\" : \"M\",\r\n" +
" \"age\" : 29,\r\n" +
" \"salary\" : 10987.77,\r\n" +
" \"married\" : false\r\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
// Pass JSON string and the POJO class
Employee employeeObject = objectMapper.readValue(jsonString, Employee.class);
// Now use getter method to retrieve values
String firsName = employeeObject.getFirstName();
String lastName = employeeObject.getLastName();
String gender = employeeObject.getGender();
int age = employeeObject.getAge();
double salary = employeeObject.getSalary();
boolean married = employeeObject.getMarried();
System.out.println("Details of Employee is as below:-");
System.out.println("First Name : "+firsName);
System.out.println("Last Name : "+lastName);
System.out.println("Gender : "+gender);
System.out.println("Age : "+age);
System.out.println("Salary : "+salary);
System.out.println("Married : "+married);
}
}
De-Serialization – JSON Object To Java Object Using Gson API
When we request an API it may return a response body which is mostly JSON or XML. We can use Jsonpath or Xmlpath to traverse through nodes to fetch specific values but it is not advisable if the response is bigger or heavily nested. We can parse that JSON or XML response into POJO classes. After parsing into POJO classes, we can easily get values from response easily. This is called De-serialization. For this, we can use any JSON parser APIs. In this post, we will use Gson API which is more famous. I have already discussed Serialization and de-serialization using Jackson API.
About GSON
As per Gson official document, Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
- Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
- Allow pre-existing unmodifiable objects to be converted to and from JSON
- Extensive support of Java Generics
- Allow custom representations for objects
- Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Gson library provides a class called “Gson“. This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.
You can create a Gson instance by invoking new Gson(), if the default configuration is all you need. You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty-printing, custom JsonSerializer, JsonDeserializer, and InstanceCreator
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
JSON String
{
"firstName" : "Amod",
"lastName" : "Mahajan",
"gender" : "M",
"age" : 29,
"salary" : 10987.77,
"married" : false
}
We need to parse above JSON string to Java Object. To create a Java object we need a class i.e. one or multiple POJO classes based on the requirement. Let’s create a class with field name exactly (case sensitive) the same as node names in above JSON string because with default setting while parsing JSON object o Java object, it will look on getter setter methods of field names. In fact, access specifiers do not matter here. We will cover some interesting facts on it later.
package SerializationDeserialization;
public class Employee {
private String firstName;
private String lastName;
private String gender;
private int age;
private double salary;
private boolean married;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public boolean getMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
JSON Sring to POJO
Gson class provides multiple overloaded fromJson() methods to achieve this. below is a list of available methods:-
We will learn how to de-serialize a JSON string and a .json file to Java object. I have stored a .json file in my project as below:-
package SerializationDeserialization;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.gson.Gson;
public class DeserializeJsonToJavaObjectUsingGson {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException, FileNotFoundException {
// De-serializing from JSON String
String jsonString = "{\r\n" + " \"firstName\" : \"Amod\",\r\n" + " \"lastName\" : \"Mahajan\",\r\n"
+ " \"gender\" : \"M\",\r\n" + " \"age\" : 29,\r\n" + " \"salary\" : 10987.77,\r\n"
+ " \"married\" : false\r\n" + "}";
Gson gson = new Gson();
// Pass JSON string and the POJO class
Employee employeeObject = gson.fromJson(jsonString, Employee.class);
// Now use getter method to retrieve values
String firsName = employeeObject.getFirstName();
String lastName = employeeObject.getLastName();
String gender = employeeObject.getGender();
int age = employeeObject.getAge();
double salary = employeeObject.getSalary();
boolean married = employeeObject.getMarried();
System.out.println("Details of Employee is as below:-");
System.out.println("First Name : " + firsName);
System.out.println("Last Name : " + lastName);
System.out.println("Gender : " + gender);
System.out.println("Age : " + age);
System.out.println("Salary : " + salary);
System.out.println("Married : " + married);
// De-serializing from a json file
String userDir = System.getProperty("user.dir");
File inputJsonFile = new File(userDir + "\\src\\test\\resources\\EmployeePayloadUsingGson.json");
FileReader fileReader = new FileReader(inputJsonFile);
Employee employeeObject1 = gson.fromJson(fileReader, Employee.class);
// Now use getter method to retrieve values
String firsName1 = employeeObject1.getFirstName();
String lastName1 = employeeObject1.getLastName();
String gender1 = employeeObject1.getGender();
int age1 = employeeObject1.getAge();
double salary1 = employeeObject1.getSalary();
boolean married1 = employeeObject1.getMarried();
System.out.println("Details of Employee from json file is as below:-");
System.out.println("First Name : " + firsName1);
System.out.println("Last Name : " + lastName1);
System.out.println("Gender : " + gender1);
System.out.println("Age : " + age1);
System.out.println("Salary : " + salary1);
System.out.println("Married : " + married1);
}
}
Output
Details of Employee is as below:-
First Name : Amod
Last Name : Mahajan
Gender : M
Age : 29
Salary : 10987.77
Married : false
Details of Employee from json file is as below:-
First Name : Amod
Last Name : Mahajan
Gender : M
Age : 29
Salary : 10987.77
Married : false