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.
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.
Below is the class JsonConverter which will parse this object into JSON.
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace JsonPluto
- {
- /// <summary>
- /// Class to convert object into json
- /// </summary>
- public class JsonConverter
- {
- /// <summary>
- /// To Serialize a object
- /// </summary>
- /// <param name="obj">object for serialization</param>
- /// <returns>json string of object</returns>
- public static string Serialize(object obj)
- {
- ///// To parse base class object
- var json = ParsePreDefinedClassObject(obj);
- ///// Null means it is not a base class object
- if (!string.IsNullOrEmpty(json))
- {
- return json;
- }
- //// For parsing user defined class object
- //// To get all properties of object
- //// and then store object properties and their value in dictionary container
- var objectDataContainer = obj.GetType().GetProperties().ToDictionary(i => i.Name, i => i.GetValue(obj));
- StringBuilder jsonfile = new StringBuilder();
- jsonfile.Append("{");
- foreach (var data in objectDataContainer)
- {
- jsonfile.Append($"\"{data.Key}\":{Serialize(data.Value)},");
- }
- //// To remove last comma
- jsonfile.Remove(jsonfile.Length - 1, 1);
- jsonfile.Append("}");
- return jsonfile.ToString();
- }
- /// <summary>
- /// To Serialize C# Pre defined classes
- /// </summary>
- /// <param name="obj">object for serialization</param>
- /// <returns>json string of object</returns>
- private static string ParsePreDefinedClassObject(object obj)
- {
- if(obj is null)
- {
- return "null";
- }
- if (IsJsonValueType(obj))
- {
- return obj.ToString().ToLower();
- }
- else if (IsJsonStringType(obj))
- {
- return $"\"{obj.ToString()}\"";
- }
- else if (obj is IDictionary)
- {
- return SearlizeDictionaryObject((IDictionary)obj);
- }
- else if (obj is IList || obj is Array)
- {
- return SearlizeListObject((IEnumerable)obj);
- }
- return null;
- }
- /// <summary>
- /// To Serialize Dictionary type object
- /// </summary>
- /// <param name="obj">object for serialization</param>
- /// <returns>json string of object</returns>
- private static string SearlizeDictionaryObject(IDictionary dict)
- {
- StringBuilder jsonfile = new StringBuilder();
- jsonfile.Append("{");
- var keysAsJson = new List<string>();
- var valuesAsJson = new List<string>();
- foreach (var item in (IEnumerable)dict.Keys)
- {
- keysAsJson.Add(Serialize(item));
- }
- foreach (var item in (IEnumerable)dict.Values)
- {
- valuesAsJson.Add(Serialize(item));
- }
- for (int i = 0; i < dict.Count; i++)
- {
- ////To check whether data is under double quotes or not
- keysAsJson[i] = keysAsJson[i].Contains("\"") ? keysAsJson[i] : $"\"{keysAsJson[i]}\"";
- jsonfile.Append($"{keysAsJson[i]}:{valuesAsJson[i]},");
- }
- jsonfile.Remove(jsonfile.Length - 1, 1);
- jsonfile.Append("}");
- return jsonfile.ToString();
- }
- /// <summary>
- /// To Serialize Enumerable (IList,Array..etc) type object
- /// </summary>
- /// <param name="obj">object for serialization</param>
- /// <returns>json string of object</returns>
- private static string SearlizeListObject(IEnumerable obj)
- {
- StringBuilder jsonfile = new StringBuilder();
- jsonfile.Append("[");
- foreach (var item in obj)
- {
- jsonfile.Append($"{Serialize(item)},");
- }
- jsonfile.Remove(jsonfile.Length - 1, 1);
- jsonfile.Append("]");
- return jsonfile.ToString();
- }
- private static bool IsJsonStringType(object obj)
- {
- return obj is string || obj is DateTime;
- }
- private static bool IsJsonValueType(object obj)
- {
- return obj.GetType().IsPrimitive;
- }
- }
- }
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.
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.
- using System;
- using System.Collections.Generic;
- namespace JsonConverterTest.Models
- {
- public class Comapany
- {
- public string Name { get; set; }
- public double TotalAsset { get; set; }
- public int TotalEmployee { get; set; }
- public bool IsGovtOrganisation { get; set; }
- public DateTime Established { get; set; }
- public List<Branch> Branches { get; set; }
- public Dictionary<string,Department> Departments { get; set; }
- public Management Management { get; set; }
- }
- public class Branch
- {
- public string Country { get; set; }
- public string State { get; set; }
- public Location Address { get; set; }
- }
- public class Location
- {
- public string BuildingName { get; set; }
- public string Street { get; set; }
- public int ZipCode { get; set; }
- }
- public class Department
- {
- public int DeptId { get; set; }
- public string DeptName { get; set; }
- }
- public class Management
- {
- public string CEO { get; set; }
- public string Founder { get; set; }
- }
- }
Step 3
Add a test project to your solution and now in test method, create a "Company" class instance and parse into JSON string.
Add a test project to your solution and now in test method, create a "Company" class instance and parse into JSON string.
- using System;
- using System.Collections.Generic;
- using JsonConverterTest.Models;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using JsonPluto;
- namespace JsonConverterTest
- {
- [TestClass]
- public class UnitTest1
- {
- /// <summary>
- /// To Get a instance of object Company
- /// </summary>
- /// <returns>instance of company</returns>
- private Comapany GetCompanyObject()
- {
- return new Comapany
- {
- Name = "CSG Solutions India Pvt Ltd",
- TotalEmployee = 50,
- Established = DateTime.Now,
- IsGovtOrganisation = false,
- TotalAsset = 20000000,
- Branches = new List<Branch>
- {
- new Branch
- {
- Country = "India",
- State = "Karnataka",
- Address = new Location
- {
- BuildingName = "Sri Hari Tower",
- Street = "2nd Main Road",
- ZipCode = 560016
- }
- },
- new Branch
- {
- Country = "USA",
- State = "Germantown",
- Address = new Location
- {
- BuildingName = "Zinc Tower",
- Street = "Germantown Road",
- ZipCode = 50001
- }
- }
- },
- Departments = new Dictionary<string, Department>
- {
- { "Engineering", new Department { DeptId = 001, DeptName = "Super Engineers" } },
- { "Support", new Department { DeptId = 002, DeptName = "24*7 Tech Support" } },
- { "Marketings", new Department { DeptId = 003, DeptName = "Tech Mavens" } }
- },
- Management = new Management { CEO = "Tarun Kumar Rajak", Founder = "Ashok Kisku" }
- };
- }
- /// <summary>
- /// To Test Serialize functionality
- /// </summary>
- [TestMethod]
- public void TestMethod1()
- {
- var json = JsonConverter.Serialize(GetCompanyObject());
- System.IO.File.WriteAllText(@"C:\Users\Public\Documents\Company.json", json);
- }
- }
- }
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.
- {
- "Name": "CSG Solutions India Pvt Ltd",
- "TotalAsset": 20000000,
- "TotalEmployee": 50,
- "IsGovtOrganisation": false,
- "Established": "29-03-2018 21:52:37",
- "Branches": [
- {
- "Country": "India",
- "State": "Karnataka",
- "Address": {
- "BuildingName": "Sri Hari Tower",
- "Street": "2nd Main Road",
- "ZipCode": 560016
- }
- },
- {
- "Country": "USA",
- "State": "Germantown",
- "Address": {
- "BuildingName": "Zinc Tower",
- "Street": "Germantown Road",
- "ZipCode": 50001
- }
- }
- ],
- "Departments": {
- "Engineering": {
- "DeptId": 1,
- "DeptName": "Super Engineers"
- },
- "Support": {
- "DeptId": 2,
- "DeptName": "24*7 Tech Support"
- },
- "Marketings": {
- "DeptId": 3,
- "DeptName": "Tech Mavens"
- }
- },
- "Management": {
- "CEO": "Tarun Kumar Rajak",
- "Founder": "Ashok Kisku"
- }
- }
In the next article, I will demonstrate how to deserailize JSON back to C# object type. Please share your valuable feedback.

terry coePosted Mar 21, 2019, 11:31 AM
Thank you for sharing. Could you post a link to the article mentioned above, regarding deserializing the JSON document back to a c# object?
Joe WilsonPosted Mar 31, 2018, 5:11 AM
Thank you for sharing it.