Using JSON with C#

I’ve learnt a lot about JSON from my MusixMatch API project which was basically a C# wrapper for a REST API. After making a lot of mistakes, I think I’ve finally figured out the best way to convert JSON data into an object oriented format. The basic idea is that you have raw data stored in a struct that contains all the fields of the data you’re going to retrieve, and you create a class that has properties to get specific data from the JSON data.

The Data

This site provides free test API’s that you can use for well.. testing. I’m going to be using this dataset from this site. This dataset contains an array of objects, each object contains 4 properties: int userID, int id, string title, string body.

Even though it’s easy to see what items our class will contain in this case, we’ll use Json2CSharp to make sense of our data. Just paste all the Json data in it and you’ll get a class or a set of classes that represent the data. This is what we’ll get.

Even though it spat out a class, we’re going to be using a struct instead since we just need a data structure to store data. So, here’s our struct.

Utilizing The Data

We’re going to use the WebClient from the .NET framework to get all the string from the api page.

We’re going to take the help of a library called Json.Net by Newtonsoft. You can either download it from their site or use the inbuilt package manager of Visual Studio. The data that we got is basically a list of our post struct i.e. List<RawPost>. The DeserializeObject<T> method will convert the Json data into our List<RawPost>.

Improving Structure

Even though we can use the data stored in the list, it would be better to have a parent class encapsulating the RawPost struct.

We can just loop through our List<RawPost> and generate a List<Post>. So what’s the benefit of creating this wrapper class? You may not want to publicly disclose or even use all the data that you get from an API. So, creating this wrapper class allows you to pick and choose data and how you can interact with this data. Plus, in order for Json.Net to work, the variable names have to be same in the class decleration as compared to what you get from the API. So, through this property-based approach, you can call your property whatever you want and just return the data from the ‘Raw’ version that’s using the original variable name.

Summarizing

  1. Get the json data from an url through WebClient.
  2. Create a struct that contains all the fields related to the json data. (Use help from Json2CSharp)
  3. Convert the json data into the struct using JsonConvert.DeserializeObject<T> method.
  4. Create a parent class that contains an instance of the struct so you can more easily manipulate the data.

 

Other Stuff

Social

AryanMann Written by: