C# Object To JSON Parser (JSON Serializer)

In this article, I will show you how to convert a C# object into a JSON string. First of all, you must know what JSON is.
  • JSON - JavaScript Object Notation.
  • JSON is a syntax for storing and exchanging the data.
You may have come across many scenarios where you need JSON format of an object. Mainly it is used in API calls for exchanging the data from API to different web applications or between browser and server. Here, I will show a simple JSON converter capable to convert most of the C# object types into JSON without using any third party and .NET serializer library. I have written converter code in a class library and then consuming this library on a test project for testing.

Notes - You must know proper JSON syntax to understand the code. 
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays 
I have kept JSON Converter class under namespace JsonPluto. Make sure to import correct namespace while testing. Serialize() method in JsonConvert class converts the C# object into a JSON string.
  • Pass the object as a parameter in Serialize method. 
  • Create a solution and add a class library project and a test project into your solution. 
Step 1

Below is the class JsonConverter which will parse this object into JSON.
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6.   
  7. namespace JsonPluto  
  8. {  
  9.     /// <summary>  
  10.     /// Class to convert object into json  
  11.     /// </summary>  
  12.     public class JsonConverter  
  13.     {  
  14.         /// <summary>  
  15.         /// To Serialize a object  
  16.         /// </summary>  
  17.         /// <param name="obj">object for serialization</param>  
  18.         /// <returns>json string of object</returns>  
  19.         public static string Serialize(object obj)  
  20.         {  
  21.             ///// To parse base class object  
  22.             var json = ParsePreDefinedClassObject(obj);  
  23.   
  24.             ///// Null means it is not a base class object  
  25.             if (!string.IsNullOrEmpty(json))  
  26.             {  
  27.                 return json;  
  28.             }  
  29.   
  30.             //// For parsing user defined class object  
  31.             //// To get all properties of object  
  32.             //// and then store object properties and their value in dictionary container  
  33.             var objectDataContainer = obj.GetType().GetProperties().ToDictionary(i => i.Name, i => i.GetValue(obj));  
  34.   
  35.             StringBuilder jsonfile = new StringBuilder();  
  36.             jsonfile.Append("{");  
  37.             foreach (var data in objectDataContainer)  
  38.             {  
  39.                 jsonfile.Append($"\"{data.Key}\":{Serialize(data.Value)},");  
  40.             }  
  41.   
  42.             //// To remove last comma  
  43.             jsonfile.Remove(jsonfile.Length - 1, 1);  
  44.             jsonfile.Append("}");  
  45.             return jsonfile.ToString();  
  46.         }  
  47.   
  48.         /// <summary>  
  49.         /// To Serialize C# Pre defined classes  
  50.         /// </summary>  
  51.         /// <param name="obj">object for serialization</param>  
  52.         /// <returns>json string of object</returns>  
  53.         private static string ParsePreDefinedClassObject(object obj)  
  54.         {  
  55.             if(obj is null)  
  56.             {  
  57.                 return "null";  
  58.             }  
  59.             if (IsJsonValueType(obj))  
  60.             {  
  61.                 return obj.ToString().ToLower();  
  62.             }  
  63.             else if (IsJsonStringType(obj))  
  64.             {  
  65.                 return $"\"{obj.ToString()}\"";  
  66.             }  
  67.             else if (obj is IDictionary)  
  68.             {  
  69.                 return SearlizeDictionaryObject((IDictionary)obj);  
  70.             }  
  71.             else if (obj is IList || obj is Array)  
  72.             {  
  73.                 return SearlizeListObject((IEnumerable)obj);  
  74.             }  
  75.   
  76.             return null;  
  77.         }  
  78.   
  79.         /// <summary>  
  80.         /// To Serialize Dictionary type object  
  81.         /// </summary>  
  82.         /// <param name="obj">object for serialization</param>  
  83.         /// <returns>json string of object</returns>  
  84.         private static string SearlizeDictionaryObject(IDictionary dict)  
  85.         {  
  86.             StringBuilder jsonfile = new StringBuilder();  
  87.             jsonfile.Append("{");  
  88.             var keysAsJson = new List<string>();  
  89.             var valuesAsJson = new List<string>();  
  90.             foreach (var item in (IEnumerable)dict.Keys)  
  91.             {  
  92.                 keysAsJson.Add(Serialize(item));  
  93.             }  
  94.             foreach (var item in (IEnumerable)dict.Values)  
  95.             {  
  96.                 valuesAsJson.Add(Serialize(item));  
  97.             }  
  98.             for (int i = 0; i < dict.Count; i++)  
  99.             {  
  100.                 ////To check whether data is under double quotes or not  
  101.                 keysAsJson[i] = keysAsJson[i].Contains("\"") ? keysAsJson[i] : $"\"{keysAsJson[i]}\"";  
  102.   
  103.                 jsonfile.Append($"{keysAsJson[i]}:{valuesAsJson[i]},");  
  104.             }  
  105.             jsonfile.Remove(jsonfile.Length - 1, 1);  
  106.             jsonfile.Append("}");  
  107.             return jsonfile.ToString();  
  108.         }  
  109.   
  110.         /// <summary>  
  111.         /// To Serialize Enumerable (IList,Array..etc) type object  
  112.         /// </summary>  
  113.         /// <param name="obj">object for serialization</param>  
  114.         /// <returns>json string of object</returns>  
  115.         private static string SearlizeListObject(IEnumerable obj)  
  116.         {  
  117.             StringBuilder jsonfile = new StringBuilder();  
  118.             jsonfile.Append("[");  
  119.             foreach (var item in obj)  
  120.             {  
  121.                 jsonfile.Append($"{Serialize(item)},");  
  122.             }  
  123.             jsonfile.Remove(jsonfile.Length - 1, 1);  
  124.             jsonfile.Append("]");  
  125.             return jsonfile.ToString();  
  126.         }  
  127.   
  128.         private static bool IsJsonStringType(object obj)  
  129.         {  
  130.             return obj is string || obj is DateTime;  
  131.         }  
  132.   
  133.         private static bool IsJsonValueType(object obj)  
  134.         {  
  135.             return obj.GetType().IsPrimitive;  
  136.         }  
  137.     }  
  138. }   
Step 2

For testing, we will write a sample models class using all types of data type like int, string, double, bool, List, Dictionary, Object etc. to create the object instance. I have created a model class named "Company" to store the company information.
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace JsonConverterTest.Models  
  5. {  
  6.     public class Comapany  
  7.     {  
  8.         public string Name { get; set; }  
  9.         public double TotalAsset { get; set; }  
  10.         public int TotalEmployee { get; set; }  
  11.         public bool IsGovtOrganisation { get; set; }  
  12.         public DateTime Established { get; set; }  
  13.         public List<Branch> Branches { get; set; }  
  14.         public Dictionary<string,Department> Departments { get; set; }  
  15.         public Management Management { get; set; }  
  16.   
  17.     }  
  18.   
  19.     public class Branch  
  20.     {  
  21.         public string Country { get; set; }  
  22.         public string State { get; set; }  
  23.         public Location Address { get; set; }  
  24.   
  25.     }  
  26.   
  27.     public class Location  
  28.     {  
  29.         public string BuildingName { get; set; }  
  30.         public string Street { get; set; }  
  31.         public int ZipCode { get; set; }  
  32.     }  
  33.   
  34.     public class Department  
  35.     {  
  36.         public int DeptId { get; set; }  
  37.         public string DeptName { get; set; }  
  38.     }  
  39.   
  40.     public class Management  
  41.     {  
  42.         public string CEO { get; set; }  
  43.         public string Founder { get; set; }  
  44.     }  
  45. }  
Step 3

Add a test project to your solution and now in test method,  create a "Company" class instance and parse into JSON string. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using JsonConverterTest.Models;  
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  5. using JsonPluto;  
  6.   
  7. namespace JsonConverterTest  
  8. {  
  9.     [TestClass]  
  10.     public class UnitTest1  
  11.     {  
  12.         /// <summary>  
  13.         /// To Get a instance of object Company  
  14.         /// </summary>  
  15.         /// <returns>instance of company</returns>  
  16.         private Comapany GetCompanyObject()  
  17.         {  
  18.             return new Comapany  
  19.             {  
  20.                 Name = "CSG Solutions India Pvt Ltd",  
  21.                 TotalEmployee = 50,  
  22.                 Established = DateTime.Now,  
  23.                 IsGovtOrganisation = false,  
  24.                 TotalAsset = 20000000,  
  25.                 Branches = new List<Branch>  
  26.                 {  
  27.                     new Branch  
  28.                     {  
  29.                         Country = "India",  
  30.                         State = "Karnataka",  
  31.                         Address = new Location  
  32.                         {  
  33.                             BuildingName = "Sri Hari Tower",  
  34.                             Street = "2nd Main Road",  
  35.                             ZipCode = 560016  
  36.                         }  
  37.                     },  
  38.                     new Branch  
  39.                     {  
  40.                         Country = "USA",  
  41.                         State = "Germantown",  
  42.                         Address = new Location  
  43.                         {  
  44.                             BuildingName = "Zinc Tower",  
  45.                             Street = "Germantown Road",  
  46.                             ZipCode = 50001  
  47.                         }  
  48.                     }  
  49.                 },  
  50.                 Departments = new Dictionary<string, Department>  
  51.                 {  
  52.                     { "Engineering"new Department { DeptId = 001, DeptName = "Super Engineers" } },  
  53.                     { "Support"new Department { DeptId = 002, DeptName = "24*7 Tech Support" } },  
  54.                     { "Marketings"new Department { DeptId = 003, DeptName = "Tech Mavens" } }  
  55.                 },  
  56.                 Management = new Management { CEO = "Tarun Kumar Rajak", Founder = "Ashok Kisku" }  
  57.             };  
  58.         }  
  59.   
  60.         /// <summary>  
  61.         /// To Test Serialize functionality  
  62.         /// </summary>  
  63.         [TestMethod]  
  64.         public void TestMethod1()  
  65.         {  
  66.             var json = JsonConverter.Serialize(GetCompanyObject());  
  67.             System.IO.File.WriteAllText(@"C:\Users\Public\Documents\Company.json", json);  
  68.         }  
  69.     }  
  70. }  
Step 4

Now, run the test method. For that, right-click the test method and click on "Run Test" or "Debug Test" option. Check the output file saved in path C:\Users\Public\Documents\Company.json.

The output file will be like below.
  1. {  
  2.   "Name""CSG Solutions India Pvt Ltd",  
  3.   "TotalAsset": 20000000,  
  4.   "TotalEmployee": 50,  
  5.   "IsGovtOrganisation"false,  
  6.   "Established""29-03-2018 21:52:37",  
  7.   "Branches": [  
  8.     {  
  9.       "Country""India",  
  10.       "State""Karnataka",  
  11.       "Address": {  
  12.         "BuildingName""Sri Hari Tower",  
  13.         "Street""2nd Main Road",  
  14.         "ZipCode": 560016  
  15.       }  
  16.     },  
  17.     {  
  18.       "Country""USA",  
  19.       "State""Germantown",  
  20.       "Address": {  
  21.         "BuildingName""Zinc Tower",  
  22.         "Street""Germantown Road",  
  23.         "ZipCode": 50001  
  24.       }  
  25.     }  
  26.   ],  
  27.   "Departments": {  
  28.     "Engineering": {  
  29.       "DeptId": 1,  
  30.       "DeptName""Super Engineers"  
  31.     },  
  32.     "Support": {  
  33.       "DeptId": 2,  
  34.       "DeptName""24*7 Tech Support"  
  35.     },  
  36.     "Marketings": {  
  37.       "DeptId": 3,  
  38.       "DeptName""Tech Mavens"  
  39.     }  
  40.   },  
  41.   "Management": {  
  42.     "CEO""Tarun Kumar Rajak",  
  43.     "Founder""Ashok Kisku"  
  44.   }  
  45. }  
In the next article, I will demonstrate how to deserailize JSON back to C# object type. Please share your valuable feedback.


Similar Articles