Using JSON with C#

As I wanted to create a C# wrapper for the MusixMatch REST API, I’ve had some time to reflect on how to store and fetch the raw data. The basic premise is that you store the deserialized results (which you get from your favorite JSON parsing library) in a struct and then use properties to expose selected values to the program. Since JSON is inherently meant to store objects, converting the data into object oriented classes does not require much thought.

The Data

JSON Placeholder provides free test API’s that you can use for while developmet. I’m going to be using this dataset from this site which contains an array of objects where 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 specific case, we shall use Json2CSharp to automatically convert our data set into C# classes. This is what we’ll get.

Even though it produces 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 the api page as a string.

Then we are going to utilize a library called Json.Net by Newtonsoft. You can either download it from their site or use the inbuilt package manager (Nuget) of Visual Studio. The data that we got is essentially a list of our RawPost 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 declaration 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: