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. namespace JsonPluto
  7. {
  8. /// <summary>
  9. /// Class to convert object into json
  10. /// </summary>
  11. public class JsonConverter
  12. {
  13. /// <summary>
  14. /// To Serialize a object
  15. /// </summary>
  16. /// <param name="obj">object for serialization</param>
  17. /// <returns>json string of object</returns>
  18. public static string Serialize(object obj)
  19. {
  20. ///// To parse base class object
  21. var json = ParsePreDefinedClassObject(obj);
  22. ///// Null means it is not a base class object
  23. if (!string.IsNullOrEmpty(json))
  24. {
  25. return json;
  26. }
  27. //// For parsing user defined class object
  28. //// To get all properties of object
  29. //// and then store object properties and their value in dictionary container
  30. var objectDataContainer = obj.GetType().GetProperties().ToDictionary(i => i.Name, i => i.GetValue(obj));
  31. StringBuilder jsonfile = new StringBuilder();
  32. jsonfile.Append("{");
  33. foreach (var data in objectDataContainer)
  34. {
  35. jsonfile.Append($"\"{data.Key}\":{Serialize(data.Value)},");
  36. }
  37. //// To remove last comma
  38. jsonfile.Remove(jsonfile.Length - 1, 1);
  39. jsonfile.Append("}");
  40. return jsonfile.ToString();
  41. }
  42. /// <summary>
  43. /// To Serialize C# Pre defined classes
  44. /// </summary>
  45. /// <param name="obj">object for serialization</param>
  46. /// <returns>json string of object</returns>
  47. private static string ParsePreDefinedClassObject(object obj)
  48. {
  49. if(obj is null)
  50. {
  51. return "null";
  52. }
  53. if (IsJsonValueType(obj))
  54. {
  55. return obj.ToString().ToLower();
  56. }
  57. else if (IsJsonStringType(obj))
  58. {
  59. return $"\"{obj.ToString()}\"";
  60. }
  61. else if (obj is IDictionary)
  62. {
  63. return SearlizeDictionaryObject((IDictionary)obj);
  64. }
  65. else if (obj is IList || obj is Array)
  66. {
  67. return SearlizeListObject((IEnumerable)obj);
  68. }
  69. return null;
  70. }
  71. /// <summary>
  72. /// To Serialize Dictionary type object
  73. /// </summary>
  74. /// <param name="obj">object for serialization</param>
  75. /// <returns>json string of object</returns>
  76. private static string SearlizeDictionaryObject(IDictionary dict)
  77. {
  78. StringBuilder jsonfile = new StringBuilder();
  79. jsonfile.Append("{");
  80. var keysAsJson = new List<string>();
  81. var valuesAsJson = new List<string>();
  82. foreach (var item in (IEnumerable)dict.Keys)
  83. {
  84. keysAsJson.Add(Serialize(item));
  85. }
  86. foreach (var item in (IEnumerable)dict.Values)
  87. {
  88. valuesAsJson.Add(Serialize(item));
  89. }
  90. for (int i = 0; i < dict.Count; i++)
  91. {
  92. ////To check whether data is under double quotes or not
  93. keysAsJson[i] = keysAsJson[i].Contains("\"") ? keysAsJson[i] : $"\"{keysAsJson[i]}\"";
  94. jsonfile.Append($"{keysAsJson[i]}:{valuesAsJson[i]},");
  95. }
  96. jsonfile.Remove(jsonfile.Length - 1, 1);
  97. jsonfile.Append("}");
  98. return jsonfile.ToString();
  99. }
  100. /// <summary>
  101. /// To Serialize Enumerable (IList,Array..etc) type object
  102. /// </summary>
  103. /// <param name="obj">object for serialization</param>
  104. /// <returns>json string of object</returns>
  105. private static string SearlizeListObject(IEnumerable obj)
  106. {
  107. StringBuilder jsonfile = new StringBuilder();
  108. jsonfile.Append("[");
  109. foreach (var item in obj)
  110. {
  111. jsonfile.Append($"{Serialize(item)},");
  112. }
  113. jsonfile.Remove(jsonfile.Length - 1, 1);
  114. jsonfile.Append("]");
  115. return jsonfile.ToString();
  116. }
  117. private static bool IsJsonStringType(object obj)
  118. {
  119. return obj is string || obj is DateTime;
  120. }
  121. private static bool IsJsonValueType(object obj)
  122. {
  123. return obj.GetType().IsPrimitive;
  124. }
  125. }
  126. }
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. namespace JsonConverterTest.Models
  4. {
  5. public class Comapany
  6. {
  7. public string Name { get; set; }
  8. public double TotalAsset { get; set; }
  9. public int TotalEmployee { get; set; }
  10. public bool IsGovtOrganisation { get; set; }
  11. public DateTime Established { get; set; }
  12. public List<Branch> Branches { get; set; }
  13. public Dictionary<string,Department> Departments { get; set; }
  14. public Management Management { get; set; }
  15. }
  16. public class Branch
  17. {
  18. public string Country { get; set; }
  19. public string State { get; set; }
  20. public Location Address { get; set; }
  21. }
  22. public class Location
  23. {
  24. public string BuildingName { get; set; }
  25. public string Street { get; set; }
  26. public int ZipCode { get; set; }
  27. }
  28. public class Department
  29. {
  30. public int DeptId { get; set; }
  31. public string DeptName { get; set; }
  32. }
  33. public class Management
  34. {
  35. public string CEO { get; set; }
  36. public string Founder { get; set; }
  37. }
  38. }
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. namespace JsonConverterTest
  7. {
  8. [TestClass]
  9. public class UnitTest1
  10. {
  11. /// <summary>
  12. /// To Get a instance of object Company
  13. /// </summary>
  14. /// <returns>instance of company</returns>
  15. private Comapany GetCompanyObject()
  16. {
  17. return new Comapany
  18. {
  19. Name = "CSG Solutions India Pvt Ltd",
  20. TotalEmployee = 50,
  21. Established = DateTime.Now,
  22. IsGovtOrganisation = false,
  23. TotalAsset = 20000000,
  24. Branches = new List<Branch>
  25. {
  26. new Branch
  27. {
  28. Country = "India",
  29. State = "Karnataka",
  30. Address = new Location
  31. {
  32. BuildingName = "Sri Hari Tower",
  33. Street = "2nd Main Road",
  34. ZipCode = 560016
  35. }
  36. },
  37. new Branch
  38. {
  39. Country = "USA",
  40. State = "Germantown",
  41. Address = new Location
  42. {
  43. BuildingName = "Zinc Tower",
  44. Street = "Germantown Road",
  45. ZipCode = 50001
  46. }
  47. }
  48. },
  49. Departments = new Dictionary<string, Department>
  50. {
  51. { "Engineering", new Department { DeptId = 001, DeptName = "Super Engineers" } },
  52. { "Support", new Department { DeptId = 002, DeptName = "24*7 Tech Support" } },
  53. { "Marketings", new Department { DeptId = 003, DeptName = "Tech Mavens" } }
  54. },
  55. Management = new Management { CEO = "Tarun Kumar Rajak", Founder = "Ashok Kisku" }
  56. };
  57. }
  58. /// <summary>
  59. /// To Test Serialize functionality
  60. /// </summary>
  61. [TestMethod]
  62. public void TestMethod1()
  63. {
  64. var json = JsonConverter.Serialize(GetCompanyObject());
  65. System.IO.File.WriteAllText(@"C:\Users\Public\Documents\Company.json", json);
  66. }
  67. }
  68. }
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.