Table of Contents
  • Rest Assured Tutorial
    • Index
  • Client Server Basics
    • Client Server Architecture and HTTP Protocol
    • What is HTTP Request?
    • What is HTTP Response?
  • RESTful Basics
    • What is REST?
    • What is Rest Api?
    • Rest Architectural Elements
  • REST API Testing - Basics
    • What is Rest Assured?
    • Configure Eclipse
    • REST API Test
    • Validate Response Status
    • Validate Response Header
    • Read JSON Response Body
    • Query Parameters
  • REST API Testing - Advance
    • POST Request
    • Serialization and Deserialization
    • Deserialize Json Response
    • Authentication and Authorization
    • Basic Authentication
    • PUT Request
    • DELETE Request
  • JSON Manipulations
    • What is JSON?
    • JSONPath and Query JSON using JSONPath
    • Expressions in JSONPath
    • Deserialize JSON Array to List
    • Deserialize JSON Array to an Array
  • REST API Framework
    • What is API Documentation?
    • REST API End to End Test
    • REST API Test in Cucumber
    • Convert JSON Request Body to POJO
    • Convert JSON Response Body to POJO
    • Separation of Test Layer with API Services
    • Implementation of REST Routes
    • Implementation of Generics in API Framework
    • Refactoring for Request Headers
    • Sharing Test Context
    • Sharing Scenario Context
    • Implement Configuration Reader
  • Blogs
    • Rest Assured Examples
  • Rest Assured Tutorial
    • Index
  • Client Server Basics
    • Client Server Architecture and HTTP Protocol
    • What is HTTP Request?
    • What is HTTP Response?
  • RESTful Basics
    • What is REST?
    • What is Rest Api?
    • Rest Architectural Elements
  • REST API Testing - Basics
    • What is Rest Assured?
    • Configure Eclipse
    • REST API Test
    • Validate Response Status
    • Validate Response Header
    • Read JSON Response Body
    • Query Parameters
  • REST API Testing - Advance
    • POST Request
    • Serialization and Deserialization
    • Deserialize Json Response
    • Authentication and Authorization
    • Basic Authentication
    • PUT Request
    • DELETE Request
  • JSON Manipulations
    • What is JSON?
    • JSONPath and Query JSON using JSONPath
    • Expressions in JSONPath
    • Deserialize JSON Array to List
    • Deserialize JSON Array to an Array
  • REST API Framework
    • What is API Documentation?
    • REST API End to End Test
    • REST API Test in Cucumber
    • Convert JSON Request Body to POJO
    • Convert JSON Response Body to POJO
    • Separation of Test Layer with API Services
    • Implementation of REST Routes
    • Implementation of Generics in API Framework
    • Refactoring for Request Headers
    • Sharing Test Context
    • Sharing Scenario Context
    • Implement Configuration Reader
  • Blogs
    • Rest Assured Examples
Enroll in Selenium Training

In this chapter, we will implement the Deserialization of JSON Responses we receive. It helps us to read the body of the response. Subsequently, in this process of deserialization, we will Convert JSON Response Body to Java Objects. It is also known as Object Representation of JSON responses.

Additionally, to learn more about the deserialization of JSON response, we will recommend you to go through the Deserialize JSON Response.

We will follow the below steps to achieve the deserialization of our responses in the framework. We followed them in the previous chapter of Convert JSON Request Body to Java Object聽as well.

  1. Create POJO classes for each of our Response Objects:
  • Book
  • Books
  • Token
  • User Account
  1. Replace the Response bodies in Step files with POJO class objects
  2. Run the tests

Convert JSON Response Body to Java Object

Firstly, we need to convert the JSON Response聽into a POJO class for our response object. So, let us learn to create a POJO class out of a JSON Response. Under deserialization, we will study our JSON body parameters and create a POJO class of it.聽 Let's begin with a straightforward request example for Get A Book request:

Create POJO class Book

As a part of this request, we are sending the ISBN parameter to get details of a specific book.

Convert JSON Response Body to Java Object Example

Consequently, the response body from the Swagger Bookstore API, as highlighted in the above image is:

{
  "books": [
    {
      "isbn": "9781449325862",
      "title": "Git Pocket Guide",
      "subTitle": "A Working Introduction",
      "author": "Richard E. Silverman",
      "published": "2013-08-02T00:00:00",
      "publisher": "O'Reilly Media",
      "pages": 234,
      "description": "This pocket guide is the perfect on-the-job companion to Git, the distributed version control system. It provides a compact, readable introduction to Git for new users, as well as a reference to common commands and procedures for those of you with Git experience.",
      "website": "https://chimera.labs.oreilly.com/books/1230000000561/index.html"
    }
}

As a part of the next step, we will create a POJO class for our response object. Additionally, you may use the same online utility, as we discussed in the previous chapter, to convert the response to a POJO class.

To create a POJO class of it, follow the below steps:

1. Firstly, Right-click on the model Package under the apiEngine package. After that, select New>>Class. Name it as Book. Moreover, we will capture the book response under this class.

Book.class

package apiEngine.model;

public class Book {
    public String isbn;
    public String title;
    public String subTitle;
    public String author;
    public String published;
    public String publisher;
    public int pages;
    public String description;
    public String website;
}

Code Explanation

This Book class will contain all the fields we got in the response, such as title, isbn, author, no.of pages, etc.

Create a POJO class for Books Response Object:

The response body from the Bookstore API, as highlighted in the below image is:

Convert JSON Response Body to Java Object

{
  "userID": "9b5f49ab-eea9-45f4-9d66-bcf56a531b85",
  "userName": "TOOLSQA-Test",
  "books": [
    {
      "isbn": "9781449325862",
      "title": "Git Pocket Guide",
      "subTitle": "A Working Introduction",
      "author": "Richard E. Silverman",
      "published": "2013-08-02T00:00:00",
      "publisher": "O'Reilly Media",
      "pages": 234,
      "description": "This pocket guide is the perfect on-the-job companion to Git, the distributed version control system. It provides a compact, readable introduction to Git for new users, as well as a reference to common commands and procedures for those of you with Git experience.",
      "website": "https://chimera.labs.oreilly.com/books/1230000000561/index.html"
    }
  ]
}

Note: As a part of the response body, we got the book details of the book we added for the user as well as other user details such as userName and userID.

To create a POJO class of it, follow the below steps:

  1. Firstly, in this model Package, Right-click on the model聽and select聽New >> Package. Name it as responses.聽 Additionally, we will capture all the response classes under this package.

  2. Secondly, Right-click聽on the above-created responses Package and select聽New >> Class. Name it as Books.

Books.class

package apiEngine.model.responses;

import java.util.List;
import apiEngine.model.Book;

public class Books {
	 public List<Book> books;
}

Code Explanation We created the class Books to hold a list of the type Book which we receive in the JSON response in GET Books Request.

Create a POJO class for Token Object:

We have understood the process of creating a POJO class by now, as shown in the above examples. So, in the next APIs, I will directly add the POJO of respective API's. Consequently, the response body for Generate Token API from our Bookstore API聽is:

{
  "token": "string",
  "expires": "2020-03-14T13:42:15.716Z",
  "status": "string",
  "result": "string"
}

To create a POJO class of it, Right-click on the above-created responses聽Package and select聽New >> Class. After that, name it as Token.

package apiEngine.model.responses;

public class Token {
	 public String token;
	 public String expires;
	 public String status;
	 public String result;
}

Code Explanation

We created the class Token that will contain all the fields we got in the response field, namely, token, expiry, status, and a result which we receive in the JSON response of GenerateToken.

Create a POJO class for User Account Object:

Similarly, for User Account API, the response body is:

{
  "userID": "9b5f49ab-eea9-45f4-9d66-bcf56a531b85",
  "userName": "TOOLSQA-Test",
  "books": []
}

To create a POJO class of the response body, Right-click on the above-created responses聽Package. After that, select New >> Class. Name it as UserAccount.

package apiEngine.model.responses;

import java.util.List;
import apiEngine.model.Book;

public class UserAccount {
    public String userID;
    public String userName;
    public List<Book> books;
}

Code Explanation

We created the class UserAccount to hold the information associated with the user account, such as books associated with the user, the userID, and userName.

As our next step of project implementation, we shall modify our Steps class.

Replace the Response bodies in Step files with POJO class objects

Now it is the time to make use of the POJO classes created above in the test code. Let's have a look at the one of the old cucumber step below in the Step Definition:

    @Given("^I am an authorized user$")
    public void iAmAnAuthorizedUser() {
        AuthorizationRequest credentials = new AuthorizationRequest("TOOLSQA-Test","Test@@123");

        RestAssured.baseURI = BASE_URL;
        RequestSpecification request = RestAssured.given();

        request.header("Content-Type", "application/json");
        response = request.body(credentials).post("/Account/v1/GenerateToken");

        String jsonString = response.asString();
       //We will deserialize the Response body into Token Response
        token = JsonPath.from(jsonString).get("token");
    }

we update it likewise:

  @Given("^I am an authorized user$")
    public void iAmAnAuthorizedUser() {

        RestAssured.baseURI = BASE_URL;
        RequestSpecification request = RestAssured.given();

        request.header("Content-Type", "application/json");
        AuthorizationRequest authRequest = new AuthorizationRequest("TOOLSQA-Test", "Test@@123");

        response = request.body(authRequest).post("/Account/v1/GenerateToken");

        // Deserializing the Response body into tokenResponse
        tokenResponse = response.getBody().as(Token.class);
    }

Note The import statement: import io.restassured.path.json.JsonPath; is no longer needed as we have deserialized our response to Token class.

Code Explanation:聽We deserialized the response body into the Token class in this step above. This response body gets saved in the "tokenResponse" variable. The saved variable will be used further in a request along with the token.

We put together these code snippets for our Steps file:

package stepDefinitions;

import java.util.List;
import java.util.Map;

import org.junit.Assert;

import apiEngine.model.Book;
import apiEngine.model.requests.AddBooksRequest;
import apiEngine.model.requests.AuthorizationRequest;
import apiEngine.model.requests.ISBN;
import apiEngine.model.requests.RemoveBookRequest;
import apiEngine.model.response.Books;
import apiEngine.model.response.Token;
import apiEngine.model.response.UserAccount;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class Steps {
	private static final String USER_ID = "9b5f49ab-eea9-45f4-9d66-bcf56a531b85";
	private static final String BASE_URL = "https://bookstore.toolsqa.com";

	private static Response response; 
	private static Token tokenResponse; 
	private static Book book;


	@Given("I am an authorized user")
	public void iAmAnAuthorizedUser() {
		AuthorizationRequest credentials = new AuthorizationRequest("TOOLSQA-Test","Test@@123");

		RestAssured.baseURI = BASE_URL;
		RequestSpecification request = RestAssured.given();

		request.header("Content-Type", "application/json");
		response = request.body(credentials).post("/Account/v1/GenerateToken");
		
		// Deserializing the Response body into tokenResponse 
		tokenResponse = response.getBody().as(Token.class);
	}

	@Given("A list of books are available")
	public void listOfBooksAreAvailable() {
		RestAssured.baseURI = BASE_URL;
		RequestSpecification request = RestAssured.given();
		
		response = request.get("/BookStore/v1/Books");

		// Deserializing the Response body into Books class 
		Books books = response.getBody().as(Books.class); 
		book = books.books.get(0);	   
	}

	@When("I add a book to my reading list")
	public void addBookInList() {
		ISBN isbn = new ISBN(book.isbn);
		AddBooksRequest addBooksRequest = new AddBooksRequest(USER_ID, isbn);
		
		RestAssured.baseURI = BASE_URL;
		RequestSpecification request = RestAssured.given();
		request.header("Authorization", "Bearer " + tokenResponse.token)
		.header("Content-Type", "application/json");

		response = request.body(addBooksRequest).post("/BookStore/v1/Books");
	}

	@Then("The book is added")
	public void bookIsAdded() {
		Assert.assertEquals(201, response.getStatusCode());
		
		UserAccount userAccount = response.getBody().as(UserAccount.class); 
		
		Assert.assertEquals(USER_ID, userAccount.userID); 
		Assert.assertEquals(book.isbn, userAccount.books.get(0).isbn);
	}

	@When("I remove a book from my reading list")
	public void removeBookFromList() {	
		RestAssured.baseURI = BASE_URL;
		RequestSpecification request = RestAssured.given();
		
		RemoveBookRequest removeBookRequest = new RemoveBookRequest(USER_ID, book.isbn);

		request.header("Authorization", "Bearer " + tokenResponse.token)
		.header("Content-Type", "application/json");

		response = request.body(removeBookRequest).delete("/BookStore/v1/Book");
	}

	@Then("The book is removed")
	public void bookIsRemoved() {
		Assert.assertEquals(204, response.getStatusCode());

		RestAssured.baseURI = BASE_URL;
		RequestSpecification request = RestAssured.given();

		request.header("Authorization", "Bearer " + tokenResponse.token)
		.header("Content-Type", "application/json");

		response = request.get("/Account/v1/User/" + USER_ID);
		Assert.assertEquals(200, response.getStatusCode());

		UserAccount userAccount = response.getBody().as(UserAccount.class);
		Assert.assertEquals(0, userAccount.books.size());
	}
}

Run the Cucumber Test

Run the Tests as JUnit

We are all set now to run the updated Cucumber test. First, Right -Click聽on聽TestRunner聽class and Click聽Run As聽 >>聽JUnit Test. Cucumber runs the script in the same way as Selenium WebDriver. 聽Consequently, the result will display in the JUnit tab of the console.

Image: Chapter 4 Junit Results

Run the Tests from Cucumber Feature

To run the tests as a Cucumber Feature, right-click on the End2End_Test.feature file. After that, select the Run As>>Cucumber Feature.

Image: Chapter 4 Cucumber Results

Our tests passed with the changes we made for the conversion of the JSON Response Body to Java Object. Please try to implement it in your framework, as explained above, and share your valuable feedback.

After creating the above POJO classes, the project folder structure will look likewise:

Project Structure Response classes

Subsequently, we will attempt the separation of Test Layer with API Services in our next chapter.

Convert JSON Request Body to JAVA Object
Convert JSON Request Body to JAVA Object
Previous Article
Separation of Test Layer with API Services
Separation of Test Layer with API Services
Next Article

Similar Articles

Validate Response Status using Rest Assured
Validate Response Status using Rest Assured
By Lakshay Sharma
9 min read
How to Validate Response Status using Rest Assured? Steps to verify Response Status Code with Rest Assured. How to test response status code in API Testing? how to add assert on Status code?
Rest Assured Examples
Rest Assured Examples
By Shilpa Nadkarni
5 min read
Rest Assured examples for various HTTP request methods such as GET, POST, PUT and DELETE. Learn with hands-on code snippets.
Basic Authentication
Basic Authentication
By Gunjan Kaushik
8 min read
How to use headers for basic authentication in rest assured? What types of authentication does rest assured support?
PUT Request using Rest Assured
PUT Request using Rest Assured
By Yashraj Gore
7 min read
What is PUT request and How it is different from the POST? How to send a PUT Request using Rest Assured in automating REST API Testing?
What is Rest Api?
What is Rest Api?
By Shilpa Nadkarni
7 min read
REST API (or RESTful API) have transformed the way we carry data from one machine to another. Learn their basics with hands-on experience.
Rest Assured Tutorial
Rest Assured Tutorial
By Lakshay Sharma
2 min read
Rest Assured Tutorial for REST API Automation Testing. API testing using Rest Assured library. How to do REST API Testing? How to do Automation Testing for REST API using Rest Assured library. Automation Testing with Rest Assured.
Deserialize JSON Response using Rest Assured
Deserialize JSON Response using Rest Assured
By Shilpa Nadkarni
9 min read
Learn how to serialize and deserialize JSON responses using REST Assured library with example codes and Live API.
REST API Testing using Rest Assured
REST API Testing using Rest Assured
By Shilpa Nadkarni
11 min read
What is REST API testing and how to perform it using REST Assured library? Understanding HTTP Methods and Status Codes.
Getting started with Rest Assured
Getting started with Rest Assured
By Shilpa Nadkarni
6 min read
What is rest assured library? Why do we need to learn it? How does rest assured help in API testing? Advantages and disadvantages.
What is REST?
What is REST?
By Shilpa Nadkarni
10 min read
What is REST and what constraints come with it? What are a client and a resource when it comes to REST services and RESTful APIs?
Feedback

两个鬼故事名人事迹婴儿起名杨姓覃起名产品免费起名的异界之华山弟子以字起名的含义cmcc是什么百度云破解版给小金毛起个名字孩子取名起名大全 五行店铺起名好听啊哪个免费起名网好火车k600免费火锅店铺起名大全600809起名沫字是什么意思在线商标起名suncity宝宝起名四个字男孩孩子起名性马三藏起名网免费取名字为公司起名无敌姑爷延禧攻略百度云资源链接靖字起名的寓意好吗cctv2直播傅姓起名字啊现代官场小说排行榜给工程机械公司起名大全笔记本摄像头驱动少年生前被连续抽血16次?多部门介入两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”淀粉肠小王子日销售额涨超10倍高中生被打伤下体休学 邯郸通报单亲妈妈陷入热恋 14岁儿子报警何赛飞追着代拍打雅江山火三名扑火人员牺牲系谣言张家界的山上“长”满了韩国人?男孩8年未见母亲被告知被遗忘中国拥有亿元资产的家庭达13.3万户19岁小伙救下5人后溺亡 多方发声315晚会后胖东来又人满为患了张立群任西安交通大学校长“重生之我在北大当嫡校长”男子被猫抓伤后确诊“猫抓病”测试车高速逃费 小米:已补缴周杰伦一审败诉网易网友洛杉矶偶遇贾玲今日春分倪萍分享减重40斤方法七年后宇文玥被薅头发捞上岸许家印被限制高消费萧美琴窜访捷克 外交部回应联合利华开始重组专访95后高颜值猪保姆胖东来员工每周单休无小长假男子被流浪猫绊倒 投喂者赔24万小米汽车超级工厂正式揭幕黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发当地回应沈阳致3死车祸车主疑毒驾恒大被罚41.75亿到底怎么缴妈妈回应孩子在校撞护栏坠楼外国人感慨凌晨的中国很安全杨倩无缘巴黎奥运校方回应护栏损坏小学生课间坠楼房客欠租失踪 房东直发愁专家建议不必谈骨泥色变王树国卸任西安交大校长 师生送别手机成瘾是影响睡眠质量重要因素国产伟哥去年销售近13亿阿根廷将发行1万与2万面值的纸币兔狲“狲大娘”因病死亡遭遇山火的松茸之乡“开封王婆”爆火:促成四五十对奥巴马现身唐宁街 黑色着装引猜测考生莫言也上北大硕士复试名单了德国打算提及普京时仅用姓名天水麻辣烫把捣辣椒大爷累坏了

两个鬼故事 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化