├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── json.sln ├── src ├── JSONParser.cs ├── JSONWriter.cs └── json.csproj └── test ├── TestParser.cs ├── TestWriter.cs └── jsontest.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | [Bb]in/ 2 | [Oo]bj/ 3 | [Dd]ebug/ 4 | [Rr]elease/ 5 | [Tt]est[Rr]esults 6 | [Tt]est-[Rr]esults/ 7 | packages/ 8 | 9 | .vs/ 10 | *.userprefs 11 | *.suo 12 | *.user 13 | *.sln.docstates 14 | *.userprefs 15 | *.meta 16 | *.obj 17 | *.pch 18 | *.pdb 19 | *.tmp 20 | *.log 21 | *.pidb 22 | *.DS_Store 23 | *.nupkg 24 | TestResult.xml 25 | 26 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | sudo: false 3 | mono: none 4 | dotnet: 2.0.3 5 | dist: trusty 6 | script: 7 | - dotnet test test/jsontest.csproj 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Alex Parker 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tiny Json 2 | 3 | [![Build Status](https://travis-ci.org/zanders3/json.png?branch=master)](https://travis-ci.org/zanders3/json) 4 | [![License](https://img.shields.io/badge/license-MIT-lightgrey.svg)](https://raw.githubusercontent.com/zanders3/json/master/LICENSE) 5 | [![NuGet](https://img.shields.io/nuget/v/TinyJson.svg)](https://www.nuget.org/packages/TinyJson) 6 | 7 | A really simple C# JSON parser in ~350 lines 8 | - Attempts to parse JSON files with minimal GC allocation 9 | - Nice and simple `"[1,2,3]".FromJson>()` API 10 | - Classes and structs can be parsed too! 11 | ```csharp 12 | class Foo 13 | { 14 | public int Value; 15 | } 16 | "{\"Value\":10}".FromJson() 17 | ``` 18 | - Anonymous JSON is parsed into `Dictionary` and `List` 19 | ```csharp 20 | var test = "{\"Value\":10}".FromJson(); 21 | int number = ((Dictionary)test)["Value"]; 22 | ``` 23 | - No JIT Emit support to support AOT compilation on iOS 24 | - Attempts are made to NOT throw an exception if the JSON is corrupted or invalid: returns null instead. 25 | - Only public fields and property setters on classes/structs will be written to 26 | - You can *optionally* use `[IgnoreDataMember]` and `[DataMember(Name="Foo")]` to ignore vars and override the default name 27 | 28 | Limitations: 29 | - No JIT Emit support to parse structures quickly 30 | - Limited to parsing <2GB JSON files (due to int.MaxValue) 31 | - Parsing of abstract classes or interfaces is NOT supported and will throw an exception. 32 | 33 | ## Changelog 34 | 35 | - v1.1 Support added for Enums and fixed Unity compilation 36 | - v1.0 Initial Release 37 | 38 | ## Example Usage 39 | 40 | This example will write a list of ints to a File and read it back again: 41 | ```csharp 42 | using System; 43 | using System.IO; 44 | using System.Collections.Generic; 45 | 46 | using TinyJson; 47 | 48 | public static class JsonTest 49 | { 50 | public static void Main(string[] args) 51 | { 52 | //Write a file 53 | List values = new List { 1, 2, 3, 4, 5, 6 }; 54 | string json = values.ToJson(); 55 | File.WriteAllText("test.json", json); 56 | 57 | //Read it back 58 | string fileJson = File.ReadAllText("test.json"); 59 | List fileValues = fileJson.FromJson>(); 60 | } 61 | } 62 | ``` 63 | Save this as `JsonTest.cs` then compile and run with `mcs JsonTest.cs && mono JsonTest.exe` 64 | 65 | ## Installation 66 | 67 | Simply copy and paste the [JSON Parser](https://raw.githubusercontent.com/zanders3/json/master/src/JSONParser.cs) and/or the [JSON Writer](https://raw.githubusercontent.com/zanders3/json/master/src/JSONWriter.cs) into your project. I also provide NuGet but I recommend the copy paste route ;) 68 | -------------------------------------------------------------------------------- /json.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio 15 3 | VisualStudioVersion = 15.0.26124.0 4 | MinimumVisualStudioVersion = 15.0.26124.0 5 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "json", "src\json.csproj", "{63C018A7-2E1D-441E-A722-26E59D0D336D}" 6 | EndProject 7 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "jsontest", "test\jsontest.csproj", "{CFA5CDCC-8818-4A06-B180-39D6E133C28B}" 8 | EndProject 9 | Global 10 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 11 | Debug|Any CPU = Debug|Any CPU 12 | Debug|x64 = Debug|x64 13 | Debug|x86 = Debug|x86 14 | Release|Any CPU = Release|Any CPU 15 | Release|x64 = Release|x64 16 | Release|x86 = Release|x86 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Debug|x64.ActiveCfg = Debug|Any CPU 22 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Debug|x64.Build.0 = Debug|Any CPU 23 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Debug|x86.ActiveCfg = Debug|Any CPU 24 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Debug|x86.Build.0 = Debug|Any CPU 25 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Release|x64.ActiveCfg = Release|Any CPU 28 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Release|x64.Build.0 = Release|Any CPU 29 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Release|x86.ActiveCfg = Release|Any CPU 30 | {63C018A7-2E1D-441E-A722-26E59D0D336D}.Release|x86.Build.0 = Release|Any CPU 31 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Debug|x64.ActiveCfg = Debug|Any CPU 34 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Debug|x64.Build.0 = Debug|Any CPU 35 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Debug|x86.ActiveCfg = Debug|Any CPU 36 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Debug|x86.Build.0 = Debug|Any CPU 37 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Release|x64.ActiveCfg = Release|Any CPU 40 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Release|x64.Build.0 = Release|Any CPU 41 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Release|x86.ActiveCfg = Release|Any CPU 42 | {CFA5CDCC-8818-4A06-B180-39D6E133C28B}.Release|x86.Build.0 = Release|Any CPU 43 | EndGlobalSection 44 | GlobalSection(SolutionProperties) = preSolution 45 | HideSolutionNode = FALSE 46 | EndGlobalSection 47 | GlobalSection(ExtensibilityGlobals) = postSolution 48 | SolutionGuid = {D0016E18-D79A-4D76-AE01-3B589F783591} 49 | EndGlobalSection 50 | EndGlobal 51 | -------------------------------------------------------------------------------- /src/JSONParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using System.Text; 7 | 8 | namespace TinyJson 9 | { 10 | // Really simple JSON parser in ~300 lines 11 | // - Attempts to parse JSON files with minimal GC allocation 12 | // - Nice and simple "[1,2,3]".FromJson>() API 13 | // - Classes and structs can be parsed too! 14 | // class Foo { public int Value; } 15 | // "{\"Value\":10}".FromJson() 16 | // - Can parse JSON without type information into Dictionary and List e.g. 17 | // "[1,2,3]".FromJson().GetType() == typeof(List) 18 | // "{\"Value\":10}".FromJson().GetType() == typeof(Dictionary) 19 | // - No JIT Emit support to support AOT compilation on iOS 20 | // - Attempts are made to NOT throw an exception if the JSON is corrupted or invalid: returns null instead. 21 | // - Only public fields and property setters on classes/structs will be written to 22 | // 23 | // Limitations: 24 | // - No JIT Emit support to parse structures quickly 25 | // - Limited to parsing <2GB JSON files (due to int.MaxValue) 26 | // - Parsing of abstract classes or interfaces is NOT supported and will throw an exception. 27 | public static class JSONParser 28 | { 29 | [ThreadStatic] static Stack> splitArrayPool; 30 | [ThreadStatic] static StringBuilder stringBuilder; 31 | [ThreadStatic] static Dictionary> fieldInfoCache; 32 | [ThreadStatic] static Dictionary> propertyInfoCache; 33 | 34 | public static T FromJson(this string json) 35 | { 36 | // Initialize, if needed, the ThreadStatic variables 37 | if (propertyInfoCache == null) propertyInfoCache = new Dictionary>(); 38 | if (fieldInfoCache == null) fieldInfoCache = new Dictionary>(); 39 | if (stringBuilder == null) stringBuilder = new StringBuilder(); 40 | if (splitArrayPool == null) splitArrayPool = new Stack>(); 41 | 42 | //Remove all whitespace not within strings to make parsing simpler 43 | stringBuilder.Length = 0; 44 | for (int i = 0; i < json.Length; i++) 45 | { 46 | char c = json[i]; 47 | if (c == '"') 48 | { 49 | i = AppendUntilStringEnd(true, i, json); 50 | continue; 51 | } 52 | if (char.IsWhiteSpace(c)) 53 | continue; 54 | 55 | stringBuilder.Append(c); 56 | } 57 | 58 | //Parse the thing! 59 | return (T)ParseValue(typeof(T), stringBuilder.ToString()); 60 | } 61 | 62 | static int AppendUntilStringEnd(bool appendEscapeCharacter, int startIdx, string json) 63 | { 64 | stringBuilder.Append(json[startIdx]); 65 | for (int i = startIdx + 1; i < json.Length; i++) 66 | { 67 | if (json[i] == '\\') 68 | { 69 | if (appendEscapeCharacter) 70 | stringBuilder.Append(json[i]); 71 | stringBuilder.Append(json[i + 1]); 72 | i++;//Skip next character as it is escaped 73 | } 74 | else if (json[i] == '"') 75 | { 76 | stringBuilder.Append(json[i]); 77 | return i; 78 | } 79 | else 80 | stringBuilder.Append(json[i]); 81 | } 82 | return json.Length - 1; 83 | } 84 | 85 | //Splits { :, : } and [ , ] into a list of strings 86 | static List Split(string json) 87 | { 88 | List splitArray = splitArrayPool.Count > 0 ? splitArrayPool.Pop() : new List(); 89 | splitArray.Clear(); 90 | if (json.Length == 2) 91 | return splitArray; 92 | int parseDepth = 0; 93 | stringBuilder.Length = 0; 94 | for (int i = 1; i < json.Length - 1; i++) 95 | { 96 | switch (json[i]) 97 | { 98 | case '[': 99 | case '{': 100 | parseDepth++; 101 | break; 102 | case ']': 103 | case '}': 104 | parseDepth--; 105 | break; 106 | case '"': 107 | i = AppendUntilStringEnd(true, i, json); 108 | continue; 109 | case ',': 110 | case ':': 111 | if (parseDepth == 0) 112 | { 113 | splitArray.Add(stringBuilder.ToString()); 114 | stringBuilder.Length = 0; 115 | continue; 116 | } 117 | break; 118 | } 119 | 120 | stringBuilder.Append(json[i]); 121 | } 122 | 123 | splitArray.Add(stringBuilder.ToString()); 124 | 125 | return splitArray; 126 | } 127 | 128 | internal static object ParseValue(Type type, string json) 129 | { 130 | if (type == typeof(string)) 131 | { 132 | if (json.Length <= 2) 133 | return string.Empty; 134 | StringBuilder parseStringBuilder = new StringBuilder(json.Length); 135 | for (int i = 1; i < json.Length - 1; ++i) 136 | { 137 | if (json[i] == '\\' && i + 1 < json.Length - 1) 138 | { 139 | int j = "\"\\nrtbf/".IndexOf(json[i + 1]); 140 | if (j >= 0) 141 | { 142 | parseStringBuilder.Append("\"\\\n\r\t\b\f/"[j]); 143 | ++i; 144 | continue; 145 | } 146 | if (json[i + 1] == 'u' && i + 5 < json.Length - 1) 147 | { 148 | UInt32 c = 0; 149 | if (UInt32.TryParse(json.Substring(i + 2, 4), System.Globalization.NumberStyles.AllowHexSpecifier, null, out c)) 150 | { 151 | parseStringBuilder.Append((char)c); 152 | i += 5; 153 | continue; 154 | } 155 | } 156 | } 157 | parseStringBuilder.Append(json[i]); 158 | } 159 | return parseStringBuilder.ToString(); 160 | } 161 | if (type.IsPrimitive) 162 | { 163 | var result = Convert.ChangeType(json, type, System.Globalization.CultureInfo.InvariantCulture); 164 | return result; 165 | } 166 | if (type == typeof(decimal)) 167 | { 168 | decimal result; 169 | decimal.TryParse(json, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result); 170 | return result; 171 | } 172 | if (type == typeof(DateTime)) 173 | { 174 | DateTime result; 175 | DateTime.TryParse(json.Replace("\"",""), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out result); 176 | return result; 177 | } 178 | if (json == "null") 179 | { 180 | return null; 181 | } 182 | if (type.IsEnum) 183 | { 184 | if (json[0] == '"') 185 | json = json.Substring(1, json.Length - 2); 186 | try 187 | { 188 | return Enum.Parse(type, json, false); 189 | } 190 | catch 191 | { 192 | return 0; 193 | } 194 | } 195 | if (type.IsArray) 196 | { 197 | Type arrayType = type.GetElementType(); 198 | if (json[0] != '[' || json[json.Length - 1] != ']') 199 | return null; 200 | 201 | List elems = Split(json); 202 | Array newArray = Array.CreateInstance(arrayType, elems.Count); 203 | for (int i = 0; i < elems.Count; i++) 204 | newArray.SetValue(ParseValue(arrayType, elems[i]), i); 205 | splitArrayPool.Push(elems); 206 | return newArray; 207 | } 208 | if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) 209 | { 210 | Type listType = type.GetGenericArguments()[0]; 211 | if (json[0] != '[' || json[json.Length - 1] != ']') 212 | return null; 213 | 214 | List elems = Split(json); 215 | var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count }); 216 | for (int i = 0; i < elems.Count; i++) 217 | list.Add(ParseValue(listType, elems[i])); 218 | splitArrayPool.Push(elems); 219 | return list; 220 | } 221 | if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) 222 | { 223 | Type keyType, valueType; 224 | { 225 | Type[] args = type.GetGenericArguments(); 226 | keyType = args[0]; 227 | valueType = args[1]; 228 | } 229 | 230 | //Refuse to parse dictionary keys that aren't of type string 231 | if (keyType != typeof(string)) 232 | return null; 233 | //Must be a valid dictionary element 234 | if (json[0] != '{' || json[json.Length - 1] != '}') 235 | return null; 236 | //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON 237 | List elems = Split(json); 238 | if (elems.Count % 2 != 0) 239 | return null; 240 | 241 | var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 }); 242 | for (int i = 0; i < elems.Count; i += 2) 243 | { 244 | if (elems[i].Length <= 2) 245 | continue; 246 | string keyValue = elems[i].Substring(1, elems[i].Length - 2); 247 | object val = ParseValue(valueType, elems[i + 1]); 248 | dictionary[keyValue] = val; 249 | } 250 | return dictionary; 251 | } 252 | if (type == typeof(object)) 253 | { 254 | return ParseAnonymousValue(json); 255 | } 256 | if (json[0] == '{' && json[json.Length - 1] == '}') 257 | { 258 | return ParseObject(type, json); 259 | } 260 | 261 | return null; 262 | } 263 | 264 | static object ParseAnonymousValue(string json) 265 | { 266 | if (json.Length == 0) 267 | return null; 268 | if (json[0] == '{' && json[json.Length - 1] == '}') 269 | { 270 | List elems = Split(json); 271 | if (elems.Count % 2 != 0) 272 | return null; 273 | var dict = new Dictionary(elems.Count / 2); 274 | for (int i = 0; i < elems.Count; i += 2) 275 | dict[elems[i].Substring(1, elems[i].Length - 2)] = ParseAnonymousValue(elems[i + 1]); 276 | return dict; 277 | } 278 | if (json[0] == '[' && json[json.Length - 1] == ']') 279 | { 280 | List items = Split(json); 281 | var finalList = new List(items.Count); 282 | for (int i = 0; i < items.Count; i++) 283 | finalList.Add(ParseAnonymousValue(items[i])); 284 | return finalList; 285 | } 286 | if (json[0] == '"' && json[json.Length - 1] == '"') 287 | { 288 | string str = json.Substring(1, json.Length - 2); 289 | return str.Replace("\\", string.Empty); 290 | } 291 | if (char.IsDigit(json[0]) || json[0] == '-') 292 | { 293 | if (json.Contains(".")) 294 | { 295 | double result; 296 | double.TryParse(json, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result); 297 | return result; 298 | } 299 | else 300 | { 301 | int result; 302 | int.TryParse(json, out result); 303 | return result; 304 | } 305 | } 306 | if (json == "true") 307 | return true; 308 | if (json == "false") 309 | return false; 310 | // handles json == "null" as well as invalid JSON 311 | return null; 312 | } 313 | 314 | static Dictionary CreateMemberNameDictionary(T[] members) where T : MemberInfo 315 | { 316 | Dictionary nameToMember = new Dictionary(StringComparer.OrdinalIgnoreCase); 317 | for (int i = 0; i < members.Length; i++) 318 | { 319 | T member = members[i]; 320 | if (member.IsDefined(typeof(IgnoreDataMemberAttribute), true)) 321 | continue; 322 | 323 | string name = member.Name; 324 | if (member.IsDefined(typeof(DataMemberAttribute), true)) 325 | { 326 | DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute), true); 327 | if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) 328 | name = dataMemberAttribute.Name; 329 | } 330 | 331 | nameToMember.Add(name, member); 332 | } 333 | 334 | return nameToMember; 335 | } 336 | 337 | static object ParseObject(Type type, string json) 338 | { 339 | object instance = FormatterServices.GetUninitializedObject(type); 340 | 341 | //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON 342 | List elems = Split(json); 343 | if (elems.Count % 2 != 0) 344 | return instance; 345 | 346 | Dictionary nameToField; 347 | Dictionary nameToProperty; 348 | if (!fieldInfoCache.TryGetValue(type, out nameToField)) 349 | { 350 | nameToField = CreateMemberNameDictionary(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); 351 | fieldInfoCache.Add(type, nameToField); 352 | } 353 | if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) 354 | { 355 | nameToProperty = CreateMemberNameDictionary(type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); 356 | propertyInfoCache.Add(type, nameToProperty); 357 | } 358 | 359 | for (int i = 0; i < elems.Count; i += 2) 360 | { 361 | if (elems[i].Length <= 2) 362 | continue; 363 | string key = elems[i].Substring(1, elems[i].Length - 2); 364 | string value = elems[i + 1]; 365 | 366 | FieldInfo fieldInfo; 367 | PropertyInfo propertyInfo; 368 | if (nameToField.TryGetValue(key, out fieldInfo)) 369 | fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value)); 370 | else if (nameToProperty.TryGetValue(key, out propertyInfo)) 371 | propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null); 372 | } 373 | 374 | return instance; 375 | } 376 | } 377 | } 378 | -------------------------------------------------------------------------------- /src/JSONWriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Reflection; 5 | using System.Runtime.Serialization; 6 | using System.Text; 7 | 8 | namespace TinyJson 9 | { 10 | //Really simple JSON writer 11 | //- Outputs JSON structures from an object 12 | //- Really simple API (new List { 1, 2, 3 }).ToJson() == "[1,2,3]" 13 | //- Will only output public fields and property getters on objects 14 | public static class JSONWriter 15 | { 16 | public static string ToJson(this object item) 17 | { 18 | StringBuilder stringBuilder = new StringBuilder(); 19 | AppendValue(stringBuilder, item); 20 | return stringBuilder.ToString(); 21 | } 22 | 23 | static void AppendValue(StringBuilder stringBuilder, object item) 24 | { 25 | if (item == null) 26 | { 27 | stringBuilder.Append("null"); 28 | return; 29 | } 30 | 31 | Type type = item.GetType(); 32 | if (type == typeof(string) || type == typeof(char)) 33 | { 34 | stringBuilder.Append('"'); 35 | string str = item.ToString(); 36 | for (int i = 0; i < str.Length; ++i) 37 | if (str[i] < ' ' || str[i] == '"' || str[i] == '\\') 38 | { 39 | stringBuilder.Append('\\'); 40 | int j = "\"\\\n\r\t\b\f".IndexOf(str[i]); 41 | if (j >= 0) 42 | stringBuilder.Append("\"\\nrtbf"[j]); 43 | else 44 | stringBuilder.AppendFormat("u{0:X4}", (UInt32)str[i]); 45 | } 46 | else 47 | stringBuilder.Append(str[i]); 48 | stringBuilder.Append('"'); 49 | } 50 | else if (type == typeof(byte) || type == typeof(sbyte)) 51 | { 52 | stringBuilder.Append(item.ToString()); 53 | } 54 | else if (type == typeof(short) || type == typeof(ushort)) 55 | { 56 | stringBuilder.Append(item.ToString()); 57 | } 58 | else if (type == typeof(int) || type == typeof(uint)) 59 | { 60 | stringBuilder.Append(item.ToString()); 61 | } 62 | else if (type == typeof(long) || type == typeof(ulong)) 63 | { 64 | stringBuilder.Append(item.ToString()); 65 | } 66 | else if (type == typeof(float)) 67 | { 68 | stringBuilder.Append(((float)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 69 | } 70 | else if (type == typeof(double)) 71 | { 72 | stringBuilder.Append(((double)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 73 | } 74 | else if (type == typeof(decimal)) 75 | { 76 | stringBuilder.Append(((decimal)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 77 | } 78 | else if (type == typeof(bool)) 79 | { 80 | stringBuilder.Append(((bool)item) ? "true" : "false"); 81 | } 82 | else if (type == typeof(DateTime)) 83 | { 84 | stringBuilder.Append('"'); 85 | stringBuilder.Append(((DateTime)item).ToString(System.Globalization.CultureInfo.InvariantCulture)); 86 | stringBuilder.Append('"'); 87 | } 88 | else if (type.IsEnum) 89 | { 90 | stringBuilder.Append('"'); 91 | stringBuilder.Append(item.ToString()); 92 | stringBuilder.Append('"'); 93 | } 94 | else if (item is IList) 95 | { 96 | stringBuilder.Append('['); 97 | bool isFirst = true; 98 | IList list = item as IList; 99 | for (int i = 0; i < list.Count; i++) 100 | { 101 | if (isFirst) 102 | isFirst = false; 103 | else 104 | stringBuilder.Append(','); 105 | AppendValue(stringBuilder, list[i]); 106 | } 107 | stringBuilder.Append(']'); 108 | } 109 | else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) 110 | { 111 | Type keyType = type.GetGenericArguments()[0]; 112 | 113 | //Refuse to output dictionary keys that aren't of type string 114 | if (keyType != typeof(string)) 115 | { 116 | stringBuilder.Append("{}"); 117 | return; 118 | } 119 | 120 | stringBuilder.Append('{'); 121 | IDictionary dict = item as IDictionary; 122 | bool isFirst = true; 123 | foreach (object key in dict.Keys) 124 | { 125 | if (isFirst) 126 | isFirst = false; 127 | else 128 | stringBuilder.Append(','); 129 | stringBuilder.Append('\"'); 130 | stringBuilder.Append((string)key); 131 | stringBuilder.Append("\":"); 132 | AppendValue(stringBuilder, dict[key]); 133 | } 134 | stringBuilder.Append('}'); 135 | } 136 | else 137 | { 138 | stringBuilder.Append('{'); 139 | 140 | bool isFirst = true; 141 | FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); 142 | for (int i = 0; i < fieldInfos.Length; i++) 143 | { 144 | if (fieldInfos[i].IsDefined(typeof(IgnoreDataMemberAttribute), true)) 145 | continue; 146 | 147 | object value = fieldInfos[i].GetValue(item); 148 | if (value != null) 149 | { 150 | if (isFirst) 151 | isFirst = false; 152 | else 153 | stringBuilder.Append(','); 154 | stringBuilder.Append('\"'); 155 | stringBuilder.Append(GetMemberName(fieldInfos[i])); 156 | stringBuilder.Append("\":"); 157 | AppendValue(stringBuilder, value); 158 | } 159 | } 160 | PropertyInfo[] propertyInfo = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy); 161 | for (int i = 0; i < propertyInfo.Length; i++) 162 | { 163 | if (!propertyInfo[i].CanRead || propertyInfo[i].IsDefined(typeof(IgnoreDataMemberAttribute), true)) 164 | continue; 165 | 166 | object value = propertyInfo[i].GetValue(item, null); 167 | if (value != null) 168 | { 169 | if (isFirst) 170 | isFirst = false; 171 | else 172 | stringBuilder.Append(','); 173 | stringBuilder.Append('\"'); 174 | stringBuilder.Append(GetMemberName(propertyInfo[i])); 175 | stringBuilder.Append("\":"); 176 | AppendValue(stringBuilder, value); 177 | } 178 | } 179 | 180 | stringBuilder.Append('}'); 181 | } 182 | } 183 | 184 | static string GetMemberName(MemberInfo member) 185 | { 186 | if (member.IsDefined(typeof(DataMemberAttribute), true)) 187 | { 188 | DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute), true); 189 | if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) 190 | return dataMemberAttribute.Name; 191 | } 192 | 193 | return member.Name; 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/json.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netcoreapp2.0 4 | true 5 | TinyJson 6 | TinyJson 7 | 1.0.0 8 | Alex Parker 9 | https://raw.githubusercontent.com/zanders3/json/master/LICENSE 10 | https://github.com/zanders3/json 11 | A really simple C# JSON parser. 12 | Copyright 2017 13 | Json;Serialisation 14 | https://github.com/zanders3/json 15 | 16 | 17 | -------------------------------------------------------------------------------- /test/TestParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.Serialization; 4 | using System.Text; 5 | using System.Threading; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | using TinyJson; 8 | 9 | namespace TinyJson.Test 10 | { 11 | [TestClass] 12 | public class TestParser 13 | { 14 | public enum Color 15 | { 16 | Red, 17 | Green, 18 | Blue, 19 | Yellow 20 | } 21 | 22 | [Flags] 23 | public enum Style 24 | { 25 | None = 0, 26 | Bold = 1, 27 | Italic = 2, 28 | Underline = 4, 29 | Strikethrough = 8 30 | } 31 | 32 | static void Test(T expected, string json) 33 | { 34 | T value = json.FromJson(); 35 | Assert.AreEqual(expected, value); 36 | } 37 | 38 | [TestMethod] 39 | public void TestValues() 40 | { 41 | Test(12345, "12345"); 42 | Test(12345L, "12345"); 43 | Test(12345UL, "12345"); 44 | Test(12.532f, "12.532"); 45 | Test(12.532m, "12.532"); 46 | Test(12.532d, "12.532"); 47 | Test("hello", "\"hello\""); 48 | Test("hello there", "\"hello there\""); 49 | Test("hello\nthere", "\"hello\nthere\""); 50 | Test("hello\"there", "\"hello\\\"there\""); 51 | Test(true, "true"); 52 | Test(false, "false"); 53 | Test(null, "sfdoijsdfoij"); 54 | Test(Color.Green, "\"Green\""); 55 | Test(Color.Blue, "2"); 56 | Test(Color.Blue, "\"2\""); 57 | Test(Color.Red, "\"sfdoijsdfoij\""); 58 | Test(Style.Bold | Style.Italic, "\"Bold, Italic\""); 59 | Test(Style.Bold | Style.Italic, "3"); 60 | Test("\u94b1\u4e0d\u591f!", "\"\u94b1\u4e0d\u591f!\""); 61 | Test("\u94b1\u4e0d\u591f!", "\"\\u94b1\\u4e0d\\u591f!\""); 62 | } 63 | 64 | static void ArrayTest(T[] expected, string json) 65 | { 66 | var value = (T[])json.FromJson(); 67 | CollectionAssert.AreEqual(expected, value); 68 | } 69 | 70 | [TestMethod] 71 | public void TestArrayOfValues() 72 | { 73 | ArrayTest(new string[] { "one", "two", "three" }, "[\"one\",\"two\",\"three\"]"); 74 | ArrayTest(new int[] { 1, 2, 3 }, "[1,2,3]"); 75 | ArrayTest(new bool[] { true, false, true }, " [true , false,true ] "); 76 | ArrayTest(new object[] { null, null }, "[null,null]"); 77 | ArrayTest(new float[] { 0.24f, 1.2f }, "[0.24,1.2]"); 78 | ArrayTest(new double[] { 0.15, 0.19 }, "[0.15, 0.19]"); 79 | ArrayTest(null, "[garbled"); 80 | } 81 | 82 | static void ListTest(List expected, string json) 83 | { 84 | var value = json.FromJson>(); 85 | CollectionAssert.AreEqual(expected, value); 86 | } 87 | 88 | [TestMethod] 89 | public void TestListOfValues() 90 | { 91 | ListTest(new List { "one", "two", "three" }, "[\"one\",\"two\",\"three\"]"); 92 | ListTest(new List { 1, 2, 3 }, "[1,2,3]"); 93 | ListTest(new List { true, false, true }, " [true , false,true ] "); 94 | ListTest(new List { null, null }, "[null,null]"); 95 | ListTest(new List { 0.24f, 1.2f }, "[0.24,1.2]"); 96 | ListTest(new List { 0.15, 0.19 }, "[0.15, 0.19]"); 97 | ListTest(null, "[garbled"); 98 | } 99 | 100 | [TestMethod] 101 | public void TestRecursiveLists() 102 | { 103 | var expected = new List> { new List { 1, 2 }, new List { 3, 4 } }; 104 | var actual = "[[1,2],[3,4]]".FromJson>>(); 105 | Assert.AreEqual(expected.Count, actual.Count); 106 | for (int i = 0; i < expected.Count; i++) 107 | CollectionAssert.AreEqual(expected[i], actual[i]); 108 | } 109 | 110 | [TestMethod] 111 | public void TestRecursiveArrays() 112 | { 113 | var expected = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } }; 114 | var actual = "[[1,2],[3,4]]".FromJson(); 115 | Assert.AreEqual(expected.Length, actual.Length); 116 | for (int i = 0; i < expected.Length; i++) 117 | CollectionAssert.AreEqual(expected[i], actual[i]); 118 | } 119 | 120 | static void DictTest(Dictionary expected, string json) 121 | { 122 | var value = json.FromJson>(); 123 | Assert.AreEqual(expected.Count, value.Count); 124 | foreach (var pair in expected) 125 | { 126 | Assert.IsTrue(value.ContainsKey(pair.Key)); 127 | Assert.AreEqual(pair.Value, value[pair.Key]); 128 | } 129 | } 130 | 131 | [TestMethod] 132 | public void TestDictionary() 133 | { 134 | DictTest(new Dictionary { { "foo", 5 }, { "bar", 10 }, { "baz", 128 } }, "{\"foo\":5,\"bar\":10,\"baz\":128}"); 135 | Assert.IsNull("{0:5}".FromJson>()); 136 | 137 | DictTest(new Dictionary { { "foo", 5f }, { "bar", 10f }, { "baz", 128f } }, "{\"foo\":5,\"bar\":10,\"baz\":128}"); 138 | DictTest(new Dictionary { { "foo", "\"" }, { "bar", "hello" }, { "baz", "," } }, "{\"foo\":\"\\\"\",\"bar\":\"hello\",\"baz\":\",\"}"); 139 | } 140 | 141 | [TestMethod] 142 | public void TestRecursiveDictionary() 143 | { 144 | var result = "{\"foo\":{ \"bar\":\"\\\"{,,:[]}\" }}".FromJson>>(); 145 | Assert.AreEqual("\"{,,:[]}", result["foo"]["bar"]); 146 | } 147 | 148 | class SimpleObject 149 | { 150 | public int A; 151 | public float B; 152 | public string C { get; set; } 153 | public List D { get; set; } 154 | } 155 | 156 | [TestMethod] 157 | public void TestSimpleObject() 158 | { 159 | SimpleObject value = "{\"A\":123,\"b\":456,\"C\":\"789\",\"D\":[10,11,12]}".FromJson(); 160 | Assert.IsNotNull(value); 161 | Assert.AreEqual(123, value.A); 162 | Assert.AreEqual(456f, value.B); 163 | Assert.AreEqual("789", value.C); 164 | CollectionAssert.AreEqual(new List { 10, 11, 12 }, value.D); 165 | 166 | value = "dfpoksdafoijsdfij".FromJson(); 167 | Assert.IsNull(value); 168 | } 169 | 170 | struct SimpleStruct 171 | { 172 | public SimpleObject Obj; 173 | } 174 | 175 | [TestMethod] 176 | public void TestSimpleStruct() 177 | { 178 | SimpleStruct value = "{\"obj\":{\"A\":12345}}".FromJson(); 179 | Assert.IsNotNull(value.Obj); 180 | Assert.AreEqual(value.Obj.A, 12345); 181 | } 182 | 183 | struct TinyStruct 184 | { 185 | public int Value; 186 | } 187 | 188 | [TestMethod] 189 | public void TestListOfStructs() 190 | { 191 | var values = "[{\"Value\":1},{\"Value\":2},{\"Value\":3}]".FromJson>(); 192 | for (int i = 0; i < values.Count; i++) 193 | Assert.AreEqual(i + 1, values[i].Value); 194 | } 195 | 196 | class TestObject2 197 | { 198 | public TestObject2 A; 199 | public List B; 200 | public SimpleStruct C; 201 | } 202 | 203 | [TestMethod] 204 | public void TestDeepObject() 205 | { 206 | var value = "{\"A\":{\"A\":{\"A\":{}}}}".FromJson(); 207 | Assert.IsNotNull(value); 208 | Assert.IsNotNull(value.A); 209 | Assert.IsNotNull(value.A.A); 210 | Assert.IsNotNull(value.A.A.A); 211 | 212 | value = "{\"B\":[{},null,{\"A\":{}}]}".FromJson(); 213 | Assert.IsNotNull(value); 214 | Assert.IsNotNull(value.B); 215 | Assert.IsNotNull(value.B[0]); 216 | Assert.IsNull(value.B[1]); 217 | Assert.IsNotNull(value.B[2].A); 218 | 219 | value = "{\"C\":{\"Obj\":{\"A\":5}}}".FromJson(); 220 | Assert.IsNotNull(value); 221 | Assert.IsNotNull(value.C.Obj); 222 | Assert.AreEqual(5, value.C.Obj.A); 223 | } 224 | 225 | class TestObject3 226 | { 227 | public int A, B, C, D, E, F; 228 | public TestObject3 Z { get; set; } 229 | } 230 | 231 | [TestMethod] 232 | public void PerformanceTest() 233 | { 234 | StringBuilder builder = new StringBuilder(); 235 | builder.Append("["); 236 | const int numTests = 100000; 237 | for (int i = 0; i < numTests; i++) 238 | { 239 | builder.Append("{\"Z\":{\"F\":10}}"); 240 | if (i < numTests - 1) 241 | builder.Append(","); 242 | } 243 | builder.Append("]"); 244 | 245 | string json = builder.ToString(); 246 | var result = json.FromJson>(); 247 | for (int i = 0; i < result.Count; i++) 248 | Assert.AreEqual(10, result[i].Z.F); 249 | } 250 | 251 | [TestMethod] 252 | public void CorruptionTest() 253 | { 254 | "{{{{{{[[[]]][[,,,,]],],],]]][[nulldsfoijsfd[[]]]]]]]]]}}}}}{{{{{{{{{D{FD{FD{F{{{{{}}}XXJJJI%&:,,,,,".FromJson(); 255 | "[[,[,,[,:::[[[[[[[".FromJson>>(); 256 | "{::,[][][],::::,}".FromJson>(); 257 | } 258 | 259 | [TestMethod] 260 | public void DynamicParserTest() 261 | { 262 | List list = (List)("[0,1,2,3]".FromJson()); 263 | Assert.IsTrue(list.Count == 4 && (int)list[3] == 3); 264 | Dictionary obj = (Dictionary)("{\"Foo\":\"Bar\"}".FromJson()); 265 | Assert.IsTrue((string)obj["Foo"] == "Bar"); 266 | 267 | string testJson = "{\"A\":123,\"B\":456,\"C\":\"789\",\"D\":[10,11,12]}"; 268 | Assert.AreEqual(testJson, ((Dictionary)testJson.FromJson()).ToJson()); 269 | } 270 | 271 | public struct NastyStruct 272 | { 273 | public byte R, G, B; 274 | public NastyStruct(byte r, byte g, byte b) 275 | { 276 | R = r; G = g; B = b; 277 | } 278 | public static NastyStruct Nasty = new NastyStruct(0, 0, 0); 279 | } 280 | 281 | [TestMethod] 282 | public void TestNastyStruct() 283 | { 284 | NastyStruct s = "{\"R\":234,\"G\":123,\"B\":11}".FromJson(); 285 | Assert.AreEqual(234, s.R); 286 | Assert.AreEqual(123, s.G); 287 | Assert.AreEqual(11, s.B); 288 | } 289 | 290 | [TestMethod] 291 | public void TestEscaping() 292 | { 293 | var orig = new Dictionary { { "hello", "world\n \" \\ \b \r \\0\u263A" } }; 294 | var parsed = "{\"hello\":\"world\\n \\\" \\\\ \\b \\r \\0\\u263a\"}".FromJson>(); 295 | Assert.AreEqual(orig["hello"], parsed["hello"]); 296 | } 297 | 298 | [TestMethod] 299 | public void TestMultithread() 300 | { 301 | // Lots of threads 302 | for (int i = 0; i < 100; i++) 303 | { 304 | new Thread(() => 305 | { 306 | // Each threads has enough work to potentially hit a race condition 307 | for (int j = 0; j < 10000; j++) 308 | { 309 | TestValues(); 310 | TestArrayOfValues(); 311 | TestListOfValues(); 312 | TestRecursiveLists(); 313 | TestRecursiveArrays(); 314 | TestDictionary(); 315 | TestRecursiveDictionary(); 316 | TestSimpleObject(); 317 | TestSimpleStruct(); 318 | TestListOfStructs(); 319 | TestDeepObject(); 320 | CorruptionTest(); 321 | DynamicParserTest(); 322 | TestNastyStruct(); 323 | TestEscaping(); 324 | TestDatetime(); 325 | } 326 | }).Start(); 327 | } 328 | } 329 | 330 | class IgnoreDataMemberObject 331 | { 332 | public int A; 333 | [IgnoreDataMember] 334 | public int B; 335 | 336 | public int C { get; set; } 337 | [IgnoreDataMember] 338 | public int D { get; set; } 339 | } 340 | 341 | [TestMethod] 342 | public void TestIgnoreDataMember() 343 | { 344 | IgnoreDataMemberObject value = "{\"A\":123,\"B\":456,\"Ignored\":10,\"C\":789,\"D\":14}".FromJson(); 345 | Assert.IsNotNull(value); 346 | Assert.AreEqual(123, value.A); 347 | Assert.AreEqual(0, value.B); 348 | Assert.AreEqual(789, value.C); 349 | Assert.AreEqual(0, value.D); 350 | } 351 | 352 | class DataMemberObject 353 | { 354 | [DataMember(Name = "a")] 355 | public int A; 356 | [DataMember()] 357 | public int B; 358 | 359 | [DataMember(Name = "c")] 360 | public int C { get; set; } 361 | public int D { get; set; } 362 | } 363 | 364 | [TestMethod] 365 | public void TestDataMemberObject() 366 | { 367 | DataMemberObject value = "{\"a\":123,\"B\":456,\"c\":789,\"D\":14}".FromJson(); 368 | Assert.IsNotNull(value); 369 | Assert.AreEqual(123, value.A); 370 | Assert.AreEqual(456, value.B); 371 | Assert.AreEqual(789, value.C); 372 | Assert.AreEqual(14, value.D); 373 | } 374 | 375 | public class EnumClass 376 | { 377 | public Color Colors; 378 | public Style Style; 379 | } 380 | 381 | [TestMethod] 382 | public void TestEnumMember() 383 | { 384 | EnumClass value = "{\"Colors\":\"Green\",\"Style\":\"Bold, Underline\"}".FromJson(); 385 | Assert.IsNotNull(value); 386 | Assert.AreEqual(Color.Green, value.Colors); 387 | Assert.AreEqual(Style.Bold | Style.Underline, value.Style); 388 | 389 | value = "{\"Colors\":3,\"Style\":10}".FromJson(); 390 | Assert.IsNotNull(value); 391 | Assert.AreEqual(Color.Yellow, value.Colors); 392 | Assert.AreEqual(Style.Italic | Style.Strikethrough, value.Style); 393 | 394 | value = "{\"Colors\":\"3\",\"Style\":\"10\"}".FromJson(); 395 | Assert.IsNotNull(value); 396 | Assert.AreEqual(Color.Yellow, value.Colors); 397 | Assert.AreEqual(Style.Italic | Style.Strikethrough, value.Style); 398 | 399 | value = "{\"Colors\":\"sfdoijsdfoij\",\"Style\":\"sfdoijsdfoij\"}".FromJson(); 400 | Assert.IsNotNull(value); 401 | Assert.AreEqual(Color.Red, value.Colors); 402 | Assert.AreEqual(Style.None, value.Style); 403 | } 404 | 405 | [TestMethod] 406 | public void TestDuplicateKeys() 407 | { 408 | var parsed = @"{""hello"": ""world"", ""goodbye"": ""heaven"", ""hello"": ""hell""}".FromJson>(); 409 | /* 410 | * We expect the parser to process the (valid) JSON above containing a duplicated key. The dictionary ensures that there is 411 | * only one entry with the duplicate key. 412 | */ 413 | Assert.IsTrue(parsed.ContainsKey("hello"), "The dictionary is missing the duplicated key"); 414 | /* 415 | * We also expect the other keys in the JSON to be processed as normal 416 | */ 417 | Assert.IsTrue(parsed.ContainsKey("goodbye"), "The dictionary is missing the non-duplicated key"); 418 | /* 419 | * The parser should store the last occurring value for the given key 420 | */ 421 | Assert.AreEqual(parsed["hello"], "hell", "The parser stored an incorrect value for the duplicated key"); 422 | } 423 | 424 | [TestMethod] 425 | public void TestDuplicateKeysInAnonymousObject() 426 | { 427 | var parsed = @"{""hello"": ""world"", ""goodbye"": ""heaven"", ""hello"": ""hell""}".FromJson(); 428 | var dictionary = (Dictionary)parsed; 429 | /* 430 | * We expect the parser to process the (valid) JSON above containing a duplicated key. The dictionary ensures that there is 431 | * only one entry with the duplicate key. 432 | */ 433 | Assert.IsTrue(dictionary.ContainsKey("hello"), "The dictionary is missing the duplicated key"); 434 | /* 435 | * We also expect the other keys in the JSON to be processed as normal 436 | */ 437 | Assert.IsTrue(dictionary.ContainsKey("goodbye"), "The dictionary is missing the non-duplicated key"); 438 | /* 439 | * The parser should store the last occurring value for the given key 440 | */ 441 | Assert.AreEqual(dictionary["hello"], "hell", "The parser stored an incorrect value for the duplicated key"); 442 | } 443 | 444 | [TestMethod] 445 | public void TestDatetime() 446 | { 447 | DateTime datetime = new DateTime(2021, 8, 16, 12, 24, 08); 448 | Assert.AreEqual("\"08/16/2021 12:24:08\"".FromJson(), datetime); 449 | } 450 | } 451 | } 452 | -------------------------------------------------------------------------------- /test/TestWriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Runtime.Serialization; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using TinyJson; 6 | 7 | namespace TinyJson.Test 8 | { 9 | [TestClass] 10 | public class TestWriter 11 | { 12 | public enum Color 13 | { 14 | Red, 15 | Green, 16 | Blue, 17 | Yellow 18 | } 19 | 20 | [Flags] 21 | public enum Style 22 | { 23 | None = 0, 24 | Bold = 1, 25 | Italic = 2, 26 | Underline = 4, 27 | Strikethrough = 8 28 | } 29 | 30 | [TestMethod] 31 | public void TestValues() 32 | { 33 | Assert.AreEqual("\"\u94b1\u4e0d\u591f!\"", "\u94b1\u4e0d\u591f!".ToJson()); 34 | Assert.AreEqual("123", 123.ToJson()); 35 | Assert.AreEqual("true", true.ToJson()); 36 | Assert.AreEqual("false", false.ToJson()); 37 | Assert.AreEqual("[1,2,3]", new int[] { 1, 2, 3 }.ToJson()); 38 | Assert.AreEqual("[1,2,3]", new List { 1, 2, 3 }.ToJson()); 39 | Assert.AreEqual("\"Green\"", Color.Green.ToJson()); 40 | Assert.AreEqual("\"Green\"", ((Color)1).ToJson()); 41 | Assert.AreEqual("\"10\"", ((Color)10).ToJson()); 42 | Assert.AreEqual("\"Bold\"", Style.Bold.ToJson()); 43 | Assert.AreEqual("\"Bold, Italic\"", (Style.Bold | Style.Italic).ToJson()); 44 | Assert.AreEqual("\"19\"", (Style.Bold | Style.Italic | (Style)16).ToJson()); 45 | } 46 | 47 | [TestMethod] 48 | public void TestDicts() 49 | { 50 | Assert.AreEqual("{\"foo\":\"bar\"}", new Dictionary { { "foo", "bar" } }.ToJson()); 51 | Assert.AreEqual("{\"foo\":123}", new Dictionary { { "foo", 123 } }.ToJson()); 52 | } 53 | 54 | class SimpleObject 55 | { 56 | public SimpleObject A; 57 | public List B; 58 | public string C { get; set; } 59 | 60 | // Should not serialize 61 | private int D = 333; 62 | public static int E = 555; 63 | internal int F = 777; 64 | protected int G = 999; 65 | public const int H = 111; 66 | } 67 | 68 | struct SimpleStruct 69 | { 70 | public SimpleObject A; 71 | } 72 | 73 | class InheritedObject : SimpleObject 74 | { 75 | public int X; 76 | } 77 | 78 | [TestMethod] 79 | public void TestObjects() 80 | { 81 | Assert.AreEqual("{\"A\":{},\"B\":[1,2,3],\"C\":\"Test\"}", new SimpleObject { A = new SimpleObject(), B = new List { 1, 2, 3 }, C = "Test" }.ToJson()); 82 | Assert.AreEqual("{\"A\":{\"A\":{},\"B\":[1,2,3],\"C\":\"Test\"}}", new SimpleStruct { A = new SimpleObject { A = new SimpleObject(), B = new List { 1, 2, 3 }, C = "Test" } }.ToJson()); 83 | Assert.AreEqual("{\"X\":9,\"A\":{},\"B\":[1,2,3],\"C\":\"Test\"}", new InheritedObject { A = new SimpleObject(), B = new List { 1, 2, 3 }, C = "Test", X = 9 }.ToJson()); 84 | } 85 | 86 | public struct NastyStruct 87 | { 88 | public int R, G, B; 89 | public NastyStruct(byte r, byte g, byte b) 90 | { 91 | R = r; G = g; B = b; 92 | } 93 | public static NastyStruct Nasty = new NastyStruct(0, 0, 0); 94 | } 95 | 96 | [TestMethod] 97 | public void TestNastyStruct() 98 | { 99 | Assert.AreEqual("{\"R\":1,\"G\":2,\"B\":3}", new NastyStruct(1,2,3).ToJson()); 100 | } 101 | 102 | [TestMethod] 103 | public void TestEscaping() 104 | { 105 | Assert.AreEqual("{\"hello\":\"world\\n \\\\ \\\" \\b \\r \\u0000\u263A\"}", new Dictionary{ 106 | {"hello", "world\n \\ \" \b \r \0\u263A"} 107 | }.ToJson()); 108 | } 109 | 110 | class IgnoreDataMemberObject 111 | { 112 | [IgnoreDataMember] 113 | public int A; 114 | public int B; 115 | [IgnoreDataMember] 116 | public int C { get; set; } 117 | public int D { get; set; } 118 | } 119 | 120 | [TestMethod] 121 | public void TestIgnoreDataMemberObject() 122 | { 123 | Assert.AreEqual("{\"B\":20,\"D\":40}", new IgnoreDataMemberObject { A = 10, B = 20, C = 30, D = 40 }.ToJson()); 124 | } 125 | 126 | class DataMemberObject 127 | { 128 | [DataMember(Name = "a")] 129 | public int A; 130 | [DataMember()] 131 | public int B; 132 | [DataMember(Name = "c")] 133 | public int C { get; set; } 134 | public int D { get; set; } 135 | } 136 | 137 | [TestMethod] 138 | public void TestDataMemberObject() 139 | { 140 | Assert.AreEqual("{\"a\":10,\"B\":20,\"c\":30,\"D\":40}", new DataMemberObject { A = 10, B = 20, C = 30, D = 40 }.ToJson()); 141 | } 142 | 143 | public class EnumClass 144 | { 145 | public Color Colors; 146 | public Style Style; 147 | } 148 | 149 | [TestMethod] 150 | public void TestEnumMember() 151 | { 152 | Assert.AreEqual("{\"Colors\":\"Green\",\"Style\":\"Bold\"}", new EnumClass { Colors = Color.Green, Style = Style.Bold }.ToJson()); 153 | Assert.AreEqual("{\"Colors\":\"Green\",\"Style\":\"Bold, Underline\"}", new EnumClass { Colors = Color.Green, Style = Style.Bold | Style.Underline }.ToJson()); 154 | Assert.AreEqual("{\"Colors\":\"Blue\",\"Style\":\"Italic, Underline\"}", new EnumClass { Colors = (Color)2, Style = (Style)6 }.ToJson()); 155 | Assert.AreEqual("{\"Colors\":\"Blue\",\"Style\":\"Underline\"}", new EnumClass { Colors = (Color)2, Style = (Style)4 }.ToJson()); 156 | Assert.AreEqual("{\"Colors\":\"10\",\"Style\":\"17\"}", new EnumClass { Colors = (Color)10, Style = (Style)17 }.ToJson()); 157 | } 158 | 159 | public class PrimitiveObject 160 | { 161 | public bool Bool; 162 | public byte Byte; 163 | public sbyte SByte; 164 | public short Short; 165 | public ushort UShort; 166 | public int Int; 167 | public uint UInt; 168 | public long Long; 169 | public ulong ULong; 170 | public char Char; 171 | public float Single; 172 | public double Double; 173 | public decimal Decimal; 174 | public DateTime Time; 175 | } 176 | 177 | [TestMethod] 178 | public void TestPrimitives() 179 | { 180 | Assert.AreEqual( 181 | "{\"Bool\":true,\"Byte\":17,\"SByte\":-17,\"Short\":-123,\"UShort\":123,\"Int\":-56,\"UInt\":56,\"Long\":-34,\"ULong\":34,\"Char\":\"C\",\"Single\":4.3,\"Double\":5.6,\"Decimal\":10.1,\"Time\":\"08/16/2021 00:00:00\"}", 182 | new PrimitiveObject 183 | { 184 | Bool = true, 185 | Byte = 17, 186 | SByte = -17, 187 | Short = -123, 188 | UShort = 123, 189 | Int = -56, 190 | UInt = 56, 191 | Long = -34, 192 | ULong = 34, 193 | Char = 'C', 194 | Single = 4.3f, 195 | Double = 5.6, 196 | Decimal = 10.1M, 197 | Time = new DateTime(2021, 8, 16) 198 | }.ToJson()); 199 | } 200 | 201 | [TestMethod] 202 | public void TestDatetime() 203 | { 204 | DateTime curTime = DateTime.Now; 205 | Assert.AreEqual(curTime.ToJson(), "\"" + DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) + "\""); 206 | } 207 | 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /test/jsontest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | --------------------------------------------------------------------------------