CREATING JSON FILE
Our sample application will read a Json string and transfer its contents to a Model. Before we further discuss about Json processing we need to create a json file in this format.
The sample json consists of several objects and one array type. There is an online tool that I used always to verify if my json is valid or not, the name of the tool is JsonLint.
You’ll need to copy paste the Json data that you want to validate into the Web tool and just click the Validate JSON. So after creating the Json file, we need to create our Model so that we will have some storage of our json data. Another tool that I frequently use is JsonToCSharp.
You will just need to copy paste the json data and just click the Generate button to generate a Model.
After the generation of our Model, we will create a Class in our sample application called CompanyInformation and just paste the generated Model in it.
In our sample application today we are going to use a NuGet called Json.Net which is an extension tool used in Visual Studio mainly for Serializing and Deserialzing json data.
To install the said NuGet, open the Package Manager Console, type “Install-Package Newtonsoft.json” and press enter to automatically download its latest repositories and install it in our project.
Let’s now proceed with actual Json Serialization. So what is Serialization? It is the process of converting an object to a json string format. In our sample code below, we created a dummy object of type CompanyInformation with an array of objects called Section. This objects were based on the Model that we just created earlier.
Then after creating the said objects we used the JsonConvert.SerializeObject() method with the companyRecordSample as its parameter in order to serialize it to a json string data. The result is shown below.
Now that we have already discussed how to Serialize an Object, we will proceed to Deserializing a Json string. Json Deserialization is converting the given json string to an object like the code segment below.
We will use the JsonConvert.DeserializeObject() method with the jsonData as its parameter. The result below will automatically map the json string to the given object that we created.
There you have it folks! The basics of handling Json data through Serialization and Deserialization process in C#. You can also read some functions provided by Json.Net through their documentation and code samples through this link.
Happy Coding 🙂