API to JSON Serialization C#

API to JSON Serialization C#

ยท

2 min read

JSON stands for Javascript Object Notation, which is a format that encodes objects in a string. In JSON there is two most important part. One is Serialization and another one is you guessed it Deserialization.

What does Serialization or Deserialization even means?

In the most easiest word I can describe is, serialization means to convert an object to a string and deserialization is the convert string to an object (the opposite one).

In a nutshell, Serialization is the process of converting an object into a stream of bytes to store an object or save it into memory or a database, or even a file. If you want to know more about serialization you can see this.

So for this demo, I have created an empty Console c# application and installed Newtonsoft.Json package from NuGet Package Manager.

In this app, we are going to get data from a public API. I like programming jokes so I scrap from this ๐Ÿ˜œ๐Ÿ˜† (You can visit here to customize your public jokes API for fun though)

So to consume API from your app there are lots of packages. Each package comes with its pros and cons. We are going to explore HttpClient as it is the new kid in the town.

We are using HttpClient so we are using GetAsync(url) function to get the results from the API. As it is async method we are using .Result to get the result from the api. So responseFromApi is an instance of HttpResponseMessage, it has a status code and this library comes with quite an handful of methods to get things done more easily. Then at last we are converting this into a string (although we can convert it into many types such as byte array, stream etc).

So to type cast it into a class we are going to need a class. Lets create this class depending on the property that I will be getting from that Api and named it JokesApi.

Now the deserialization techniques come in the play. In c# Json.net comes handy when handling such things.

We are casting the string as the class type that we newly created. As we are getting one response only so we are casting as it is. If we want the list we would use IList<classtype> to cast it.

That's the console output.

You will find everything on GitHub. ๐ŸŒ™๐Ÿดโ€โ˜ ๏ธ๐Ÿ˜Ž