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

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