Skip to content

Instantly share code, notes, and snippets.

@DevBobcorn
Last active May 20, 2025 14:58
Show Gist options
  • Save DevBobcorn/aee85e88a447b2d9633d70111dcab34d to your computer and use it in GitHub Desktop.
Save DevBobcorn/aee85e88a447b2d9633d70111dcab34d to your computer and use it in GitHub Desktop.
Simple json serializer written in C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public static class Json
{
/// <summary>
/// Implement this interface if you want custom
/// json serialization for your class
/// </summary>
public interface IJSONSerializable
{
public string ToJson();
}
private static string Dictionary2Json(Dictionary<string, object> dictionary)
{
return "{" + string.Join(",", dictionary.Select(x => $"\"{x.Key}\":{ Object2Json(x.Value) }") ) + "}";
}
private static string List2Json(List<object> list)
{
return "[" + string.Join(",", list.Select(Object2Json) ) + "]";
}
private static string Array2Json(object[] array)
{
return "[" + string.Join(",", array.Select(Object2Json) ) + "]";
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj">Object to serialize</param>
public static string Object2Json(object obj)
{
return obj switch
{
// Nested object
Dictionary<string, object> dict => Dictionary2Json(dict),
// Object list
List<object> list => List2Json(list),
// Object array
object[] array => Array2Json(array),
// User-defined json serialization
IJSONSerializable objValue => objValue.ToJson(),
// String value, wrap with quotation marks
string strValue => $"\"{strValue}\"",
// Boolean value, should be lowercase 'true' or 'false'
bool boolValue => boolValue ? "true" : "false",
// Null value, should be lowercase 'null'
null => "null",
// Other types, just convert to string
_ => $"\"{obj}\""
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment