Converting Object to JSON and JSON to C# Objects

JSON is a faster and more lightweight data exchange pattern between servers and the clients.

Let us see in a demo how to convert an object to JSON and JSON Text into a C# object.

Nuget provides a plug-in called JSON.NET which provides the facility to convert this. 

 
Let us say we have a employee class as below:
  1. public class Employee  
  2. {  
  3.     public int EmployeeID  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string EmployeeName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string DeptWorking  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public int Salary  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23. }  

And we have a list of employee data; we will convert this into JSON text.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using Newtonsoft.Json;  
  4. namespace JSON  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             List < Employee > lstemployee = new List < Employee > ();  
  11.             lstemployee.Add(new Employee()  
  12.             {  
  13.                 EmployeeID = 100, EmployeeName = "Pradeep", DeptWorking = "OnLineBanking", Salary = 10000  
  14.             });  
  15.             lstemployee.Add(new Employee()  
  16.             {  
  17.                 EmployeeID = 101, EmployeeName = "Mark", DeptWorking = "OnLineBanking", Salary = 20000  
  18.             });  
  19.             lstemployee.Add(new Employee()  
  20.             {  
  21.                 EmployeeID = 102, EmployeeName = "Smith", DeptWorking = "Mobile banking", Salary = 10000  
  22.             });  
  23.             lstemployee.Add(new Employee()  
  24.             {  
  25.                 EmployeeID = 103, EmployeeName = "John", DeptWorking = "Testing", Salary = 7000  
  26.             });  
  27.             string output = JsonConvert.SerializeObject(lstemployee);  
  28.             Console.WriteLine(output);  
  29.             Console.ReadLine();  
  30.             List < Employee > deserializedProduct = JsonConvert.DeserializeObject < List < Employee >> (output);  
  31.         }  
  32.     }  
  33. }   

Output 

 We saw how we converted an object to JSON and JSON to objects. Thanks for reading.
Ebook Download
View all
Learn
View all