{"id":23447525,"url":"https://github.com/cmstar/serialization","last_synced_at":"2025-06-14T21:04:11.992Z","repository":{"id":9537236,"uuid":"11440509","full_name":"cmstar/Serialization","owner":"cmstar","description":"A light weight JSON serialization library written in C#.","archived":false,"fork":false,"pushed_at":"2022-05-09T15:48:42.000Z","size":311,"stargazers_count":2,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-26T23:05:03.836Z","etag":null,"topics":["csharp-library","json","serialization"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cmstar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-07-16T04:19:30.000Z","updated_at":"2022-05-30T08:06:01.000Z","dependencies_parsed_at":"2022-09-24T04:02:12.347Z","dependency_job_id":null,"html_url":"https://github.com/cmstar/Serialization","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/cmstar/Serialization","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmstar%2FSerialization","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmstar%2FSerialization/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmstar%2FSerialization/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmstar%2FSerialization/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cmstar","download_url":"https://codeload.github.com/cmstar/Serialization/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cmstar%2FSerialization/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259884418,"owners_count":22926441,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp-library","json","serialization"],"created_at":"2024-12-23T21:18:03.009Z","updated_at":"2025-06-14T21:04:11.970Z","avatar_url":"https://github.com/cmstar.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# cmstar.Serialization.Json\n\n[![NuGet](https://img.shields.io/nuget/v/cmstar.Serialization.Json.svg)](https://www.nuget.org/packages/cmstar.Serialization.Json/)\n\nA light weight JSON serialization library written in C#.\n\nSupported .NET platform:\n- .NET Framework 3.5\n- .NET Framework 4.x\n- All other platforms that support .NET Standard 2, such as .NET Core 2/3, .NET 5/6\n\nDependency:\n- [cmstar.RapidReflection](https://www.nuget.org/packages/cmstar.RapidReflection) To emit IL for accessing type members.\n\n## Install\n\nInstall via Package Manager:\n```\nInstall-Package cmstar.Serialization.Json\n```\n\nor via dotnet-cli:\n```\ndotnet add package cmstar.Serialization.Json\n```\n\n## JsonSerializer\n\nThe `JsonSerializer` class is the entry for serializing/deserializing.\n\n### Serialize CLR objects to JSONs\n\n```csharp\npublic class Data\n{\n    public string String { get; set; }\n    public int Int { get; set; }\n    public int[] Array { get; set; }\n}\n\nvar serializer = new JsonSerializer();\n\nserializer.Serialize(123);\n//-\u003e 123\n\nserializer.Serialize(\"Hello\\nWorld\");\n//-\u003e \"Hellow\\nWorld\"\n\nserializer.Serialize(DateTime.Now.ToUniversalTime());\n//-\u003e \"2013-07-15T14:21:05.2151663Z\"\n\nserializer.Serialize(new char[] { 'a', 'b' });\n//-\u003e [\"a\",\"b\"]\n\nserializer.Serialize(new Dictionary\u003cstring, int\u003e {\n    { \"key1\", 1 },\n    { \"key2\", 2 }\n});\n//-\u003e {\"key1\":1,\"key2\":2}\n\nserializer.Serialize(new Data { Array = new int[] { 1, 2 } });\n//-\u003e {\"String\":null,\"Int\":0,\"Array\":[1,2]}\n```\n\n### Deserialize JSONs to CLR objects\n\n```csharp\n// non-generic version\nData data = (Data)serializer.Deserialize(\n    \"{\\\"String\\\":null,\\\"Int\\\":0,\\\"Array\\\":[1,2]}\",\n    typeof(Data));\n\n// generic version\nint[] array = serializer.Deserialize\u003cint[]\u003e(\"[1,2,3]\");\n```\n\n### Anonymous Objects\n\nSerializing anonymouse objects is just the same:\n```csharp\nvar anonymousObject = new {\n    Foo = 123,\n    Bar = \"xx\",\n    Array = new int[] { 1, 2, 3 }\n};\nJsonSerializer.Default.Serialize(anonymousObject);\n//-\u003e {\"Foo\":123,\"Bar\":\"xx\",\"Array\":[1,2,3]}\n```\n\nTo deserialize, a template object should be provided:\n```csharp\nvar template = new { Foo = 0, Bar = (string)null };\nvar json = \"{\\\"Foo\\\":10,\\\"Bar\\\":\\\"s\\\"}\";\n\n// call JsonSerializer.Deserialize\u003cT\u003e(string json, T template)\nvar result = JsonSerializer.Default.Deserialize(json, template);\n```\n\n### The default JsonSerializer\n\nEach instance of `JsonSerializer` is isolated, it can keep different instances of `JsonContract` and can be customized separately from another `JsonSerializer`. But in most time, we need just one `JsonSerializer`, in the case we can use `JsonSerializer.Default`:\n```csharp\nvar json = JsonSerializer.Default.Serialize(new Data());\nvar data = JsonSerializer.Default.Deserialize\u003cData\u003e(json);\n```\n\n### Using Attributes\n\nTo serialize a POCO, by default, only public properties will be serialized.\nYou can use the `JsonPropertyAttribute` to select the members you need:\n```csharp\nclass Data\n{\n    public Data(string s) { String = s; }\n\n    [JsonProperty(\"string_value\")] // mark a private field\n    private string String;\n\n    [JsonProperty] // no name specified, will use 'Int' directly\n    public int Int { get; set; }\n\n    public int WillBeIngored { get; set; }\n}\n\nJsonSerializer.Default.Serialize(new Data(\"s\") { Int = 3 });\n//-\u003e {\"string_value\":\"s\",\"Int\":3}\n```\n\nor use `JsonIgnoreAttribute`:\n```csharp\nclass Data\n{\n    public string String { get; set; }\n\n    [JsonJsonIgnore]\n    public int Int { get; set; }\n}\n\nJsonSerializer.Default.Serialize(new Data { String = \"s\", Int = 3 });\n//-\u003e {\"String\":\"s\"}\n```\n\n\u003e Note: If you mix `JsonIgnoreAttribute` and `JsonPropertyAttribute` together, the  serializer ignores `JsonPropertyAttribute`.\n\n\u003e Note: If a property has no getter accessor (public or non-public), it will be ignored during the serialization; and the value of a property without a setter accessor will not be set.\n\n### Pretty-print JSON\n\nBy default the JSONs outputted is compact but not much human-readable. An overload of the `JsonSerializer.Serialize()` mothod accepts an argument 'formatting' which can be used to specify the format of JSON seriliazed.\n\n```csharp\nJsonSerializer.Default.Serialize(new Data { Array = new int[] { 1, 2 } });\n//-\u003e {\"String\":null,\"Int\":0,\"Array\":[1,2]}\n\nJsonSerializer.Default.Serialize(\n    new Data { Array = new int[] { 1, 2 } },\n    Formatting.Multiple);\n/* -\u003e\n{\n\"String\":null,\n\"Int\":0,\n\"Array\":[\n1,\n2\n]\n}\n*/\n\nJsonSerializer.Default.Serialize(\n    new Data { Array = new int[] { 1, 2 } },\n    Formatting.Indented);\n/* -\u003e\n{\n    \"String\":null,\n    \"Int\":0,\n    \"Array\":[\n        1,\n        2\n    ]\n}\n*/\n```\n\n### Faster Serialization\n\nFor performance need, the `JsonSerializer.FastSerialize()` method provides a faster serialization, which is about 50% faster than the `JsonSerializer.Serialize()` method.\n\nThe faster version uses the `JsonWriter` class against the `JsonWriterImproved` class used by the `JsonSerializer.Serialize()` method. See the 'JsonWriter' section below for more details.\n\n## JsonContract\n\nThe classes derive from the `JsonContract` class indicate how to serialize CLR objects or deserialize JSONs.\n\nThe table below gives out the default contracts, which will convert the CLR types to/from corresponding JSON types:\n\n|CLR type|Contract|JSON type|\n|----|----|----|\n|String|StringContract|String|\n|Char|StringContract|String|\n|Boolean|BooleanContract|Boolean|\n|SByte|NumberContarct|Number|\n|Int16|NumberContarct|Number|\n|Int32|NumberContarct|Number|\n|Int64|NumberContarct|Number|\n|Byte|NumberContarct|Number|\n|UInt16|NumberContarct|Number|\n|UInt32|NumberContarct|Number|\n|UInt64|NumberContarct|Number|\n|IntPtr|NumberContarct|Number|\n|UIntPtr|NumberContarct|Number|\n|Single|NumberContarct|Number|\n|Double|NumberContarct|Number|\n|Decimal|NumberContarct|Number|\n|DateTimeOffset|DateTimeOffsetContarct|String|\n|DateTime|DateTimeContarct|String|\n|Guid|GuidContarct|String|\n|Nullable\u0026lt;T\u0026gt;|NullableTypeContract|Depends on typeof(T)|\n|Types derived from Enum|EnumContarct|Number|\n|Implementations of IDictionary|DictionaryContarct|Object|\n|Implementations of IDictionary\u0026lt;K,V\u0026gt;|DictionaryContarct|Object|\n|Implementations of ICollection|ArrayContarct|Array|\n|Implementations of ICollection\u0026lt;T\u0026gt;|ArrayContarct|Array|\n|Other types not listed above|ObjectContarct|Object|\n\n- CLR `null` (`Nothing` in VB.net) will be serialized to JSON `null`.\n- For an object of type `Nullable\u003cT\u003e`, if has value, it will be serialized using the underlying value; otherwise, will be serialized to JSON `null`.\n- Non-generic implementations of `ICollection` or `IDictionary` can be serialized but can not be deserialized because when deserializing the application doesn't know which CLR type should be used - the JSON type to CLR type mapping is 1 to N. \n\n### JsonContractResolver\n\nThis class is used to resolve the `JsonContract`s for different types.\n\nYou can register custom `JsonContract`s by sending a dictionary to the constructor of `JsonContractResolver`:\n\n```csharp\nvar customContracts = new Dictionary\u003cType, JsonContract\u003e();\ncustomContracts.Add(typeof(Data), new CustomDataContract());\n\nvar contractResolver = new JsonContractResolver(customContracts);\nvar serializer = new JsonSerializer(contractResolver);\n```\n\nNote: You can't register custom `JsonContract`s to `JsonSerializer.Default` at present. \n\n### Serializing Dates\n\nThe default contract for `DateTime`/`DateTimeOffset` is the `DateTimeContract`/`DateTimeOffsetContract`, \nwhich will serialize dates in the ISO-8601 format `yyyy-MM-ddTHH:mm:ss.ffffffZ`, \nsuch as `2022-01-31T13:15:05.2151663-02:00`, or `2022-01-31T13:15:05.2151663Z` (UTC). \n\nYou can register `CustomFormatDateTimeOffsetContract` to customize the format, with a property `Format`, \nthe code below shows how to serialize dates in the format `yyyy~MM~dd HH:mm:ss`:\n\n`DateTimeContract` shares the format of `DateTimeOffsetContract`,\nChange the format for `DateTimeOffset` will also change the format for `DateTime`.\n\n```csharp\nvar dateTimeContract = new CustomFormatDateTimeOffsetContract();\ndateTimeContract.Format = \"yyyy~MM~dd HH@mm@ss\";\n\nvar customContracts = new Dictionary\u003cType, JsonContract\u003e();\ncustomContracts.Add(typeof(DateTimeOffset), dateTimeContract);\n\nvar contractResolver = new JsonContractResolver(customContracts);\nvar serializer = new JsonSerializer(contractResolver);\n\nserializer.Serialize(DateTimeOffset.Now);\n//-\u003e \"2013~07~15 14@41@03\"\n\n// When serializing DateTime, it shares the format.\nserializer.Serialize(DateTime.Now);\n//-\u003e \"2013~07~15 14@41@03\"\n```\n\nAnother contract provided is `MicrosoftJsonDateContract`, which formats time \nin the Miscrosoft JSON format, such as `/Date(1620142251000+0300)/`.\n\n### Serializing Enums\n\nBy default enums are serialized to JSON numbers using the index, if you need the name of an enum, you can setup the `EnumContract.UseEnumName` property to `true`.\n```csharp\nvar stringEnumContract = new EnumContract(typeof(SomEnum));\nstringEnumContract.UseEnumName = true;\n\nvar customContracts = new Dictionary\u003cType, JsonContract\u003e();\ncustomContracts.Add(typeof(SomEnum), stringEnumContract);\n\nvar contractResolver = new JsonContractResolver(customContracts);\nvar serializer = new JsonSerializer(contractResolver);\n\nserializer.Serialize(SomEnum.SomeItem);\n//-\u003e \"SomeItem\"\n```\n\n### Customize the resolving of JsonContracts\n\nHere is an example that shows how to tell the `JsonSerializer` to serialize all enums by their names.\n\nFirst, build a sub class of the `JsonContractResolver` and override the `DoResove` method which is the core method for contract resolving:\n```csharp\nclass StringEnumContractResolver : JsonContractResolver\n{\n    protected override JsonContract DoResolve(Type type)\n    {\n        if (type.IsSubclassOf(typeof(Enum)))\n            return new EnumContract(type) { UseEnumName = true };\n\n        return base.DoResolve(type);\n    }\n}\n```\n\nThen you can setup the `JsonSerializer` with the class above:\n```csharp\nvar contractResolver = new StringEnumContractResolver();\nvar serializer = new JsonSerializer(contractResolver);\n\nserializer.Serialize(SomeEnum.SomeItem);\n//-\u003e \"SomeItem\"\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmstar%2Fserialization","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcmstar%2Fserialization","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcmstar%2Fserialization/lists"}