How Do
I Deserialize a JSON Response to a Class Using Rest Sharp?
Let's
continue from the earlier section, Creating a POST request with Rest-Sharp. In
the earlier section, we made a successful post request and received the Response
body shown below.
To
validate parts of the Response body, we used JObject.Parse. We will make this
Response body into a Class. Deserialization of JSON refers to the process of
converting a JSON or any structured data, including XML, into a programming
class. Deserialization refers to the process of converting JSON from its String
form to its Class form. This is also known as structured data object
representation. JSON is used to represent
structured data in this case.
To
integrate the JSON to a Class representation, we will first create a Class that
contains all of the nodes in the JSON. There are three nodes in the
Success response above.
·
Success code
·
Type
·
Message
String is the value of these three nodes. The parts of the response are depicted in the image below.
To
portray such a Json, we will need a class with three String variables, one
for each node in the Json. The class code is listed below. Pay close attention
to the code comments for more information.
class UsersResponseData
{
public int Code { get; set; }
public string Type { get; set; }
public string Message
{ get; set; }
}
We now
have a UsersResponseData class that can hold all of the nodes in the Success
Response. Let's look at how we might use RestSharp to automatically convert
Response Body Json to a UsersResponseData class instance.
We can
get all element nodes from a string json to the required format, which in our
case is a class, by using the deserialize object method of the JsonConvert class (UsersResponseData).
JsonConvert.DeserializeObject<classname>(JSon string);
The
sample code for deserializing a json string to the responsedata class is
provided below.
UsersResponseData
responseData=JsonConvert.DeserializeObject<UsersResponseData>(response.Content);
Internally,
this method call will perform two functions.
Make a UsersResponseData
instance.
Then, in the
Class, copy the Node value of Json to the appropriate variable. For example,
the Value of Code node in the class refers to the Variable SucessCode.
Full
Code for above example
Users.feature file
Feature: Users
Operations about user
Background:
Given I perform
api operation on petstore server https://petstore.swagger.io/v2/
Scenario: Post operation with Deserualize Json response
When I perform POST operation for User using endpoint "/user" by creating createinstance
| Id | username |
firstname | lastname | email
| password | phone | userstatus |
| 5 | Karan | Karan | Arjun | karan.a@gmail.com | kararajun | 9876554345 | 1
|
Then I should see a
response message that says the same thing as equest and that it is also
successful, with a status code of 200 OK.
UsersResponseData.cs File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APIAutomation.Modules
{
public class UsersResponseData
{
public int Code { get; set; }
public string Type { get; set; }
public string Message
{ get; set; }
}
}
UsersSteps.cs File
using APIAutomation.Modules;
using APIAutomation.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting; //For asserting
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; //For Json
object creation
using RestSharp; //For RestSharp operation
using System; //for Basic C# package
using System.Data;
using TechTalk.SpecFlow; //for BDD
package
using TechTalk.SpecFlow.Assist;
namespace APIAutomation.Features
{
[Binding] //It's
binding the feature file with step definition file
public class UsersSteps
{
public RestClient client;
public RestRequest request;
public IRestResponse response;
[Given(@"I
perform api operation on petstore server ""(.*)""")]
public void
GivenIPerformApiOperationOnPetstoreServer(string baseUrl)
{
//Make a
Request that points to the Service Endpoint.
client = new RestClient(baseUrl);
}
[When(@"I perform POST operation for User using endpoint
""(.*)"" by creating createinstance")]
public void
WhenIPerformPOSTOperationForUserUsingEndpointByCreatingcreateinstance(string endpoint, Table table)
{
var values = table.CreateInstance<User>();
JObject jobj4 = new JObject();
jobj4.Add("id", values.id);
jobj4.Add("username",values.username);
jobj4.Add("firstName",values.firstName);
jobj4.Add("lastName",
values.lastName);
jobj4.Add("email", values.email);
jobj4.Add("password",values.password);
jobj4.Add("phone",values.phone);
jobj4.Add("userStatus", values.userStatus);
//Add a
JSON body to the request and send it.
request = new RestRequest(endpoint, Method.POST);
// Including the JSON body as a parameter in the post request
request.AddParameter("application/json", jobj4,
ParameterType.RequestBody);
//execute the
request
response = client.Execute(request);
}
[Then(@"I should see a response message that says the same thing
as equest and that it is also successful, with a status code of (.*) OK\.")]
public void
ThenIShouldSeeAResponseMessageThatSaysTheSameThingAsEquestAndThatItIsAlsoSuccessfulWithAStatusCodeOfOK_(int status)
{
//Converting
the response status code to integer format
int statusCode = (int)response.StatusCode;
//Deserialize
the response using class instance
UsersResponseData responseData =
JsonConvert.DeserializeObject<UsersResponseData>(response.Content);
Console.WriteLine("User Id :"+responseData.Message);
Console.WriteLine("Satus code :"+responseData.Code);
//Asserting the
response's status code
Assert.AreEqual(status, statusCode,
"Statuscode is not a " + status);
}
}
}
Output
Solution
Explorer
Json Response Deserialization >>>>> Download Now
ReplyDelete>>>>> Download Full
Json Response Deserialization >>>>> Download LINK
>>>>> Download Now
Json Response Deserialization >>>>> Download Full
>>>>> Download LINK lj