Last active
May 20, 2025 14:58
-
-
Save DevBobcorn/aee85e88a447b2d9633d70111dcab34d to your computer and use it in GitHub Desktop.
Simple json serializer written in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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