(De-)serializing JSON and XML in RestAssured.Net
This post was published on December 15, 2022In a series of (short) blog posts, I would like to share with you some examples of how to use RestAssured.Net for writing tests for RESTful and GraphQL APIs.
- Getting started and basic examples
- Parameterized tests
- (De-)serialization (this blog post)
- Authentication and reuse
- Testing GraphQL APIs
All examples that you see in this blog post series can be found on GitHub.
Serialization
Serialization is the process of creating a JSON or XML representation of a C# object. RestAssured.Net supports both JSON and XML, and in this blog post, we’ll look at examples for both.
First, consider this C# object, representing a blog post:
Now, if we want to create a JSON or an XML representation of an instance of this class, there are several ways to do that. We could, for example, build the JSON or XML ‘by hand’, however, that is error-prone and often clunky.
Therefore, we can also leverage the power of libraries like Json.Net and System.Xml, respectively, to take care of the heavy lifting for us. And that’s exactly what RestAssured.Net does for you, out of the box.
If we want to send a JSON representation of a Post
object, all we need to do is pass an instance to the Body()
method:
When we run this test and log the request to the standard output, we see that the Post
instance is serialized into this JSON payload:
Success! It also works with anonymous objects, by the way:
If we want to serialize our Post
object to XML instead of JSON, we need to set the request Content-Type
header to application/xml
:
This will result in the following XML payload to be POSTed to the endpoint:
Deserialization
We can also transform JSON or XML response payloads back into strongly typed C# objects, a process known as deserialization. In RestAssured.Net, this is done using the As()
method:
This, too, works both for JSON and XML. RestAssured.Net inspects the Content-Type
header value of the response and tries to deserialize the response according to its value, defaulting to JSON if no Content-Type
header value can be found.
That’s it for (de-)serialization and working with JSON and XML request and response payloads in RestAssured.Net. In the next blog post in this series, we’ll look at extracting and reusing request properties and response values, as well as different API authentication mechanisms supported by RestAssured.Net.
"