We can parse the JSON or XML response into POJO classes. After parsing into POJO classes, we can easily get values from the response easily. This is called De-serialization. For this, we can use any JSON parser APIs. Here, we are going to use Gson API.
To start with, add the below dependency to the project.
Let us create a class called Employee with a field name exactly (case-sensitive) the same as node names in the above JSON string because with the default setting while parsing JSON object to Java object, it will look on getter setter methods of field names.
public class Employee {
// private variables or data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Gson class provides multiple overloaded fromJson() methods to achieve this. Below is a list of available methods:-
In the below test, I have mentioned the JSON Payload string in the test and used Gson API to deserialize the JSON payload to JAVA Object.
@Test
public void getDetailFromJson() {
// De-serializing from JSON String
String jsonString = "{\r\n" + " \"firstName\": \"Tom\",\r\n" + " \"lastName\": \"John\",\r\n"
+ " \"age\": 30,\r\n" + " \"salary\": 50000.0,\r\n" + " \"designation\": \"Lead\",\r\n"
+ " \"contactNumber\": \"+917642218922\",\r\n" + " \"emailId\": \"abc@test.com\"\r\n" + "}";
Gson gson = new Gson();
// Pass JSON string and the POJO class
Employee employee = gson.fromJson(jsonString, Employee.class);
// Now use getter method to retrieve values
System.out.println("Details of Employee is as below:-");
System.out.println("First Name : " + employee.getFirstName());
System.out.println("Last Name : " + employee.getLastName());
System.out.println("Age : " + employee.getAge());
System.out.println("Salary : " + employee.getSalary());
System.out.println("designation : " + employee.getDesignation());
System.out.println("contactNumber : " + employee.getContactNumber());
System.out.println("emailId : " + employee.getEmailId());
System.out.println("########################################################");
}
The output of the above program is
We can get the JSON payload from a file present in a project under src/test/resources as shown in the below image.
public class EmployeeDeserializationGsonTest {
@Test
public void fromFile() throws FileNotFoundException {
Gson gson = new Gson();
// 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 employee1 = gson.fromJson(fileReader, Employee.class);
// Now use getter method to retrieve values
System.out.println("Details of Employee is as below:-");
System.out.println("First Name : " + employee1.getFirstName());
System.out.println("Last Name : " + employee1.getLastName());
System.out.println("Age : " + employee1.getAge());
System.out.println("Salary : " + employee1.getSalary());
System.out.println("designation : " + employee1.getDesignation());
System.out.println("contactNumber : " + employee1.getContactNumber());
System.out.println("emailId : " + employee1.getEmailId());
System.out.println("########################################################");
}
}
The output of the above program is
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Google has developed a JSON library for Java called Gson. We can create JSON and translate it into Java objects using Gson. Gson can output JSON in compact format by default. The setPrettyPrinting() function of the GsonBuilder class must be used to set up the Gson instance in order to enable pretty printing. This method tells Gson to produce JSON that fits on a page for pretty printing.
Add the below dependency to POM.xml to use Gson API.
Let us create a table named Employee which contains the data members same as node names in the above JSON payload and their corresponding getter and setter methods.
public class Employee {
// private data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
We will convert a Java Object to a JSON object as a String and also will write it into a .json file. There are many variations for the method toJson().
You can create a Gson instance by invoking a new Gson() if the default configuration is all you need, as shown in the below example.
@Test
public void withoutPretty() {
// Create an object of POJO class
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
Gson gson = new Gson();
String employeeJsonPayload = gson.toJson(employee);
System.out.println("Json :" + employeeJsonPayload);
}
The execution message is shown below.
Syntax
public GsonBuilder setPrettyPrinting()
Below is the program to print the JSON in pretty format.
@Test
public void withPretty() {
// Create an object of POJO class
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(employee);
System.out.println("Pretty Json :" + json);
}
The output of the above program is
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Let us create a table named Employee which contains the data members same as node names in the above JSON payload with @Expose annotation and their corresponding getter and setter methods.
package com.example.gson;
import com.google.gson.annotations.Expose;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
public class Employee {
// private data members of POJO class
@Expose(serialize = true)
private String firstName;
@Expose(serialize = true)
private String lastName;
@Expose(serialize = false)
private int age;
@Expose(serialize = true)
private Map<String, BigDecimal> salary;
@Expose()
private String designation;
@Expose(serialize = false)
private String contactNumber;
@Expose(serialize = true)
private List<String> emailId;
// Getter and setter methods
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Map<String, BigDecimal> getSalary() {
return salary;
}
public void setSalary(Map<String, BigDecimal> salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public List<String> getEmailId() {
return emailId;
}
public void setEmailId(List<String> emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "(firstName: " + firstName + "," +
"lastName: " + lastName + "," +
"age: " + age + ", " +
"salary: " + salary + "," +
"designation: " + designation + ", " +
"contactNumber: " + contactNumber + ", " +
"emailId: " + emailId + ")";
}
}
Suppose the attribute age and contactNumber in the Employee class should not serialize because it’s sensitive information. Hence, we must decorate these attributes with the annotation @Expose(serialize=false):
To use @Expose annotation, we must create a Gson instance by using the GsonBuilder class and its excludeFieldsWithoutExposeAnnotation() method.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class GsonExpose_Demo {
@Test
public void gsonExposeTest() {
// Create an object of POJO class
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
Map<String, BigDecimal> salary = new HashMap() {{
put("2010", new BigDecimal(10000));
put("2012", new BigDecimal(12000));
put("2018", new BigDecimal(14000));
}};
employee.setSalary(salary);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId(Arrays.asList("abc@test.com","vibha@test.com"));
Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
String employeeJsonPayload = gson.toJson(employee);
System.out.println("Json :" + employeeJsonPayload);
}
}
The output of the above program is shown below.
We can see here that age and contactNumber are not shown in the JSON body.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
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 for those you do not have source code.
Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice versa.
Add the below dependency to POM.xml to use Gson API.
Let us create a table named Employee which contains the data members same as node names in the above JSON payload and their corresponding getter and setter methods.
import java.math.BigDecimal;
import java.util.Map;
public class Employee {
// private data members of POJO class
private String firstName;
private String lastName;
private int age;
private Map<String, BigDecimal> salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Map<String, BigDecimal> getSalary() {
return salary;
}
public void setSalary(Map<String, BigDecimal> salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "(firstName: " + firstName + "," +
"lastName: " + lastName + "," +
"age: " + age + ", " +
"salary: " + salary + "," +
"designation: " + designation + ", " +
"contactNumber: " + contactNumber + ", " +
"emailId: " + emailId + ")";
}
}
We will convert a JSON Object to a Java Object.
The JSON file – Employee.json is present in src/test/resources.
Below is the image of JSON.
You can create a Gson instance by invoking a new Gson() if the default configuration is all you need, as shown in the below example.
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 those you do not have source code.
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).
Add the below dependency to POM.xml to use Gson API.
Let us create a table named Employee which contains the data members same as node names in the above JSON payload and their corresponding getter and setter methods.
public class Employee {
// private data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
We will convert a Java Object to a JSON object as a String and also will write it into a .json file. There are many variations for the method toJson().
You can create a Gson instance by invoking a new Gson() if the default configuration is all you need, as shown in the below example.
You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty-printing, custom JsonSerializer, JsonDeserializer.
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 those you do not have source code.
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).
Add the below dependency to POM.xml to use Gson API.
Let us create a table named Employee which contains the data members same as node names in the above JSON payload and their corresponding getter and setter methods.
public class Employee {
// private data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
We will convert a Java Object to a JSON object as a String and also will write it into a .json file. There are many variations for the method toJson().
You can create a Gson instance by invoking a new Gson() if the default configuration is all you need, as shown in the below example.
You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty-printing, custom JsonSerializer, JsonDeserializer.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
public class EmployeeGsonTest {
@Test
public void gsonSerializationTest() {
// Create an object of POJO class
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
Gson gson = new Gson();
String employeeJsonPayload = gson.toJson(employee);
System.out.println("Json :" + employeeJsonPayload);
Gson builder = new GsonBuilder().setPrettyPrinting().create();
String employeePrettyJsonPayload = builder.toJson(employee);
System.out.println("Pretty Json :" + employeePrettyJsonPayload);
}
}
The execution message is shown below.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
As we know, we can use toJson() to convert the JAVA objects to JSON Payload.
In the below example, I have created a POJO class with the name of EmployeeDetails. This class contains the data members corresponding to the JSON nodes and their corresponding getter and setter methods.
public class EmployeeDetails {
// private variables or data members of pojo class
private String name;
private double salary;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Below, will create a JSON payload and pass it as a request body to the Rest API.
@Test
public void createEmployee() throws IOException {
// Just create an object of Pojo class
EmployeeDetails emp = new EmployeeDetails();
emp.setName("GsonTest");
emp.setSalary(50000);
emp.setAge(25);
// Converting a Java class object to a JSON payload as string using Gson
Gson builder = new GsonBuilder().setPrettyPrinting().create();
String employeePrettyJsonPayload = builder.toJson(emp);
System.out.println("Request");
System.out.println(employeePrettyJsonPayload);
System.out.println("=========================================");
System.out.println("Response");
// GIVEN
given()
.baseUri("http://dummy.restapiexample.com/api")
.contentType(ContentType.JSON).body(emp)
// WHEN
.when()
.post("/v1/create")
// THEN
.then()
.assertThat().statusCode(200)
.body("status", equalTo("success"))
.body("data.name", equalTo("GsonTest"))
.body("data.salary", equalTo(50000))
.body("data.age", equalTo(25))
.body("message", equalTo("Successfully! Record has been added."))
.log().body();
}
}
Output
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!