Introduction
Handling JSON with C# is difficult some times. Most software developers work with Web APIs to exchange the data. JSON (JavaScript Object Notation) is one of the best way to exchange data over the HTTP protocol. JSON is simply a string, which contains the data or some important information about the receiving data. It’s a lightweight technology to pass the desired data. We simply request in the URL and API (other Sources) to pass the data in the form of JSON. Hence, in this article, I am showing how to map JSON with C# classes to access the data in the form of class and fields.
Example
I am working with a weather app. Therefore, I am taking this example; i.e., the website www.openweathermap.org/current, which provides the API, and gives the complete information about the weather.
- Go to Web and sign up
- Go to pricing and select the free package
- Generate the API key.
- We have a series of links of how to pass the information to API in the form of latitude or longitude of either zip or of either country
- Once the request is passed to the API, the weather information is passed in the form of JSON.
- I want to access the weather information of Pakistan, so the call is http://api.openweathermap.org/data/2.5/weather?q=Pakistan&appid={API Key}
- Hence, it returns the data in the form of JSON, which is shown below:
- Our aim is to convert that JSON into the C# classes and fields
- Type www.Json2csharp.com,
- Paste that JSON into the box and click Generate that web site followed by converting that JSON into C# classes and fields.
- When we click, the classes generate, which will look as follows:
- Click copy and then open the Visual Studio, and make the console project that you can use in every project like Windows form, WPF, UWP etc.
- Here, we verify it, using the console Application.
- As we see, Json2chsrp makes individual classes and the one class called Root Object contains the references of the sub classes
- RootObject class is most important, when we want to use data receiving in the form of JSON.
DataContract and DataMember Attribute
- Next step is to decorate each class with the DataContract attribute and each field of every class with the DataMemeber Attribute just like it is done in every class, as shown below:
- Afterwards, we make a function, which requests the API to async and accept the request, as shown below:
- Make a method which calls the GetRequest() Method, as shown below:
- Finally, the complete code will be:
- Verify the output, as shown below:
Conclusion
There is a simple mechanism, which is used to develop the strongly typed classes and fields with JSON; using this method, it becomes easy to parse and use JSON across the whole project.