Convert JSON To Strongly Typed Object Using DataContract In C#

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.

    name
  • 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:

    JSON

  • Our aim is to convert that JSON into the C# classes and fields
  • Type www.Json2csharp.com,

    type

  • Paste that JSON into the box and click Generate that web site followed by converting that JSON into C# classes and fields.

    Generate

  • When we click, the classes generate, which will look as follows:

    code
    code

  • 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:

    class
  • Afterwards, we make a function, which requests the API to async and accept the request, as shown below:

    code
  • Make a method which calls the GetRequest() Method, as shown below:

    Method
     
  • Finally, the complete code will be:

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.IO;  
    4. using System.Net.Http;  
    5. using System.Runtime.Serialization;  
    6. using System.Runtime.Serialization.Json;  
    7. using System.Text;  
    8. using System.Threading.Tasks;  
    9.   
    10. namespace ConsoleApplication1   
    11. {  
    12.     class Program  
    13.     {  
    14.         static void Main(string[] args)  
    15.       {  
    16.             Program program = new Program();  
    17.             program.Disaply();  
    18.             Console.ReadKey();  
    19.         }  
    20.   
    21.         public async void Disaply()  
    22.       {  
    23.             RootObject rootObject = await this.GetRequest();  
    24.             Console.WriteLine("City name is" + rootObject.name);  
    25.             Console.WriteLine("Temprature in K is" + rootObject.main.temp);  
    26.         }  
    27.         public async Task < RootObject > GetRequest()  
    28.         {  
    29.             HttpClient httpClient = new HttpClient();  
    30.             String url =  
    31.                 string.Format(  
    32.                     "http://api.openweathermap.org/data/2.5/weather?q=Pakistan&appid=84e30cdb8f3823239ed2d77f0fd013b6");  
    33.             var respose = await httpClient.GetAsync(new Uri(url));  
    34.             var result = await respose.Content.ReadAsStringAsync();  
    35.             var serializer = new DataContractJsonSerializer(typeof(RootObject));  
    36.             var MemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(result));  
    37.             var FinalData = serializer.ReadObject(MemoryStream) as RootObject;  
    38.             return FinalData;  
    39.   
    40.         }  
    41.   
    42.     }  
    43.   
    44.     [DataContract]  
    45.     public class Coord  
    46.     {  
    47.         [DataMember]  
    48.         public double lon  
    49.         {  
    50.             get;  
    51.             set;  
    52.         }  
    53.         [DataMember]  
    54.         public double lat  
    55.         {  
    56.             get;  
    57.             set;  
    58.         }  
    59.     }  
    60.     [DataContract]  
    61.     public class Weather  
    62.     {  
    63.         [DataMember]  
    64.         public int id  
    65.         {  
    66.             get;  
    67.             set;  
    68.         }  
    69.         [DataMember]  
    70.         public string main  
    71.         {  
    72.             get;  
    73.             set;  
    74.         }  
    75.         [DataMember]  
    76.         public string description  
    77.         {  
    78.             get;  
    79.             set;  
    80.         }  
    81.         [DataMember]  
    82.         public string icon   
    83.         {  
    84.             get;  
    85.             set;  
    86.         }  
    87.     }  
    88.     [DataContract]  
    89.     public class Main   
    90.     {  
    91.         [DataMember]  
    92.         public double temp   
    93.         {  
    94.             get;  
    95.             set;  
    96.         }  
    97.         [DataMember]  
    98.         public int pressure   
    99.         {  
    100.             get;  
    101.             set;  
    102.         }  
    103.         [DataMember]  
    104.         public int humidity   
    105.         {  
    106.             get;  
    107.             set;  
    108.         }  
    109.         [DataMember]  
    110.         public double temp_min   
    111.         {  
    112.             get;  
    113.             set;  
    114.         }  
    115.         [DataMember]  
    116.         public double temp_max   
    117.         {  
    118.             get;  
    119.             set;  
    120.         }  
    121.     }  
    122.     [DataContract]  
    123.     public class Wind   
    124.     {  
    125.         [DataMember]  
    126.         public double speed   
    127.         {  
    128.             get;  
    129.             set;  
    130.         }  
    131.   
    132.         [DataMember]  
    133.         public int deg   
    134.         {  
    135.             get;  
    136.             set;  
    137.         }  
    138.     }  
    139.     [DataContract]  
    140.     public class Clouds   
    141.     {  
    142.         [DataMember]  
    143.         public int all   
    144.         {  
    145.             get;  
    146.             set;  
    147.         }  
    148.     }  
    149.     [DataContract]  
    150.     public class Sys   
    151.     {  
    152.         [DataMember]  
    153.         public int type   
    154.         {  
    155.             get;  
    156.             set;  
    157.         }  
    158.         [DataMember]  
    159.           
    160.         public int id   
    161.         {  
    162.             get;  
    163.             set;  
    164.         }  
    165.         [DataMember]  
    166.         public double message   
    167.         {  
    168.             get;  
    169.             set;  
    170.         }  
    171.         [DataMember]  
    172.         public string country   
    173.         {  
    174.             get;  
    175.             set;  
    176.         }  
    177.         [DataMember]  
    178.         public int sunrise  
    179.         {  
    180.             get;  
    181.             set;  
    182.         }  
    183.         [DataMember]  
    184.         public int sunset  
    185.         {  
    186.             get;  
    187.             set;  
    188.         }  
    189.     }  
    190.     [DataContract]  
    191.     public class RootObject   
    192.     {  
    193.         [DataMember]  
    194.         public Coord coord   
    195.         {  
    196.             get;  
    197.             set;  
    198.         }  
    199.         [DataMember]  
    200.         public List < Weather > weather   
    201.         {  
    202.                 get;  
    203.                 set;  
    204.             }  
    205.             [DataMember]  
    206.         public string @base   
    207.         {  
    208.             get;  
    209.             set;  
    210.         }  
    211.         [DataMember]  
    212.         public Main main   
    213.         {  
    214.             get;  
    215.             set;  
    216.         }  
    217.         [DataMember]  
    218.         public Wind wind  
    219.         {  
    220.             get;  
    221.             set;  
    222.         }  
    223.         [DataMember]  
    224.         public Clouds clouds   
    225.         {  
    226.             get;  
    227.             set;  
    228.         }  
    229.         [DataMember]  
    230.         public int dt  
    231.         {  
    232.             get;  
    233.             set;  
    234.         }  
    235.         [DataMember]  
    236.         public Sys sys  
    237.         {  
    238.             get;  
    239.             set;  
    240.         }  
    241.         [DataMember]  
    242.         public int id   
    243.         {  
    244.             get;  
    245.             set;  
    246.         }  
    247.         [DataMember]  
    248.         public string name   
    249.         {  
    250.             get;  
    251.             set;  
    252.         }  
    253.         [DataMember]  
    254.         public int cod  
    255.         {  
    256.             get;  
    257.             set;  
    258.         }  
    259.     }  
    260.   
    261. }

  • Verify the output, as shown below:

    output

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.


Similar Articles