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;
- }
- }
- }

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.