-
Notifications
You must be signed in to change notification settings - Fork 143
/
SimpleJson.cs
2127 lines (1921 loc) · 87.1 KB
/
SimpleJson.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------
// <copyright file="SimpleJson.cs" company="The Outercurve Foundation">
// Copyright (c) 2011, The Outercurve Foundation.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.opensource.org/licenses/mit-license.php
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
// <website>https://github.com/facebook-csharp-sdk/simple-json</website>
//-----------------------------------------------------------------------
// VERSION:
// NOTE: uncomment the following line to make SimpleJson class internal.
//#define SIMPLE_JSON_INTERNAL
// NOTE: uncomment the following line to make JsonArray and JsonObject class internal.
//#define SIMPLE_JSON_OBJARRAYINTERNAL
// NOTE: uncomment the following line to enable dynamic support.
//#define SIMPLE_JSON_DYNAMIC
// NOTE: uncomment the following line to enable DataContract support.
//#define SIMPLE_JSON_DATACONTRACT
// NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support.
//#define SIMPLE_JSON_READONLY_COLLECTIONS
// NOTE: uncomment the following line to disable linq expressions/compiled lambda (better performance) instead of method.invoke().
// define if you are using .net framework <= 3.0 or < WP7.5
//#define SIMPLE_JSON_NO_LINQ_EXPRESSION
// NOTE: uncomment the following line if you are compiling under Window Metro style application/library.
// usually already defined in properties
//#define NETFX_CORE;
// If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO;
// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
#if NETFX_CORE
#define SIMPLE_JSON_TYPEINFO
#endif
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
using System.Linq.Expressions;
#endif
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#if SIMPLE_JSON_DYNAMIC
using System.Dynamic;
#endif
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using SimpleJson.Reflection;
// ReSharper disable LoopCanBeConvertedToQuery
// ReSharper disable RedundantExplicitArrayCreation
// ReSharper disable SuggestUseVarKeywordEvident
namespace SimpleJson
{
/// <summary>
/// Represents the json array.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if SIMPLE_JSON_OBJARRAYINTERNAL
internal
#else
public
#endif
class JsonArray : List<object>
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class.
/// </summary>
public JsonArray() { }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class.
/// </summary>
/// <param name="capacity">The capacity of the json array.</param>
public JsonArray(int capacity) : base(capacity) { }
/// <summary>
/// The json representation of the array.
/// </summary>
/// <returns>The json representation of the array.</returns>
public override string ToString()
{
return SimpleJson.SerializeObject(this) ?? string.Empty;
}
}
/// <summary>
/// Represents the json object.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if SIMPLE_JSON_OBJARRAYINTERNAL
internal
#else
public
#endif
class JsonObject :
#if SIMPLE_JSON_DYNAMIC
DynamicObject,
#endif
IDictionary<string, object>
{
/// <summary>
/// The internal member dictionary.
/// </summary>
private readonly Dictionary<string, object> _members;
/// <summary>
/// Initializes a new instance of <see cref="JsonObject"/>.
/// </summary>
public JsonObject()
{
_members = new Dictionary<string, object>();
}
/// <summary>
/// Initializes a new instance of <see cref="JsonObject"/>.
/// </summary>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> implementation to use when comparing keys, or null to use the default <see cref="T:System.Collections.Generic.EqualityComparer`1"/> for the type of the key.</param>
public JsonObject(IEqualityComparer<string> comparer)
{
_members = new Dictionary<string, object>(comparer);
}
/// <summary>
/// Gets the <see cref="System.Object"/> at the specified index.
/// </summary>
/// <value></value>
public object this[int index]
{
get { return GetAtIndex(_members, index); }
}
internal static object GetAtIndex(IDictionary<string, object> obj, int index)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (index >= obj.Count)
throw new ArgumentOutOfRangeException("index");
int i = 0;
foreach (KeyValuePair<string, object> o in obj)
if (i++ == index) return o.Value;
return null;
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Add(string key, object value)
{
_members.Add(key, value);
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(string key)
{
return _members.ContainsKey(key);
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys
{
get { return _members.Keys; }
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public bool Remove(string key)
{
return _members.Remove(key);
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGetValue(string key, out object value)
{
return _members.TryGetValue(key, out value);
}
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public ICollection<object> Values
{
get { return _members.Values; }
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public object this[string key]
{
get { return _members[key]; }
set { _members[key] = value; }
}
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item.</param>
public void Add(KeyValuePair<string, object> item)
{
_members.Add(item.Key, item.Value);
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
_members.Clear();
}
/// <summary>
/// Determines whether [contains] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException("array");
int num = Count;
foreach (KeyValuePair<string, object> kvp in this)
{
array[arrayIndex++] = kvp;
if (--num <= 0)
return;
}
}
/// <summary>
/// Gets the count.
/// </summary>
/// <value>The count.</value>
public int Count
{
get { return _members.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
public bool Remove(KeyValuePair<string, object> item)
{
return _members.Remove(item.Key);
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _members.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _members.GetEnumerator();
}
/// <summary>
/// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return SimpleJson.SerializeObject(this);
}
#if SIMPLE_JSON_DYNAMIC
/// <summary>
/// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
/// </summary>
/// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>
/// <param name="result">The result of the type conversion operation.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryConvert(ConvertBinder binder, out object result)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
Type targetType = binder.Type;
if ((targetType == typeof(IEnumerable)) ||
(targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
(targetType == typeof(IDictionary<string, object>)) ||
(targetType == typeof(IDictionary)))
{
result = this;
return true;
}
return base.TryConvert(binder, out result);
}
/// <summary>
/// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
/// </summary>
/// <param name="binder">Provides information about the deletion.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
return _members.Remove(binder.Name);
}
/// <summary>
/// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name="indexes"/> is equal to 3.</param>
/// <param name="result">The result of the index operation.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes == null) throw new ArgumentNullException("indexes");
if (indexes.Length == 1)
{
result = ((IDictionary<string, object>)this)[(string)indexes[0]];
return true;
}
result = null;
return true;
}
/// <summary>
/// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
object value;
if (_members.TryGetValue(binder.Name, out value))
{
result = value;
return true;
}
result = null;
return true;
}
/// <summary>
/// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="indexes"/> is equal to 3.</param>
/// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.
/// </returns>
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (indexes == null) throw new ArgumentNullException("indexes");
if (indexes.Length == 1)
{
((IDictionary<string, object>)this)[(string)indexes[0]] = value;
return true;
}
return base.TrySetIndex(binder, indexes, value);
}
/// <summary>
/// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
/// </returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
_members[binder.Name] = value;
return true;
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>
/// A sequence that contains dynamic member names.
/// </returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
foreach (var key in Keys)
yield return key;
}
#endif
}
}
namespace SimpleJson
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>).
/// All numbers are parsed to doubles.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
static class SimpleJson
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
private static readonly char[] EscapeTable;
private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
private static readonly string EscapeCharactersString = new string(EscapeCharacters);
static SimpleJson()
{
EscapeTable = new char[93];
EscapeTable['"'] = '"';
EscapeTable['\\'] = '\\';
EscapeTable['\b'] = 'b';
EscapeTable['\f'] = 'f';
EscapeTable['\n'] = 'n';
EscapeTable['\r'] = 'r';
EscapeTable['\t'] = 't';
}
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false</returns>
public static object DeserializeObject(string json)
{
object obj;
if (TryDeserializeObject(json, out obj))
return obj;
throw new SerializationException("Invalid JSON string");
}
/// <summary>
/// Try parsing the json string into a value.
/// </summary>
/// <param name="json">
/// A JSON string.
/// </param>
/// <param name="obj">
/// The object.
/// </param>
/// <returns>
/// Returns true if successfull otherwise false.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
public static bool TryDeserializeObject(string json, out object obj)
{
bool success = true;
if (json != null)
{
char[] charArray = json.ToCharArray();
int index = 0;
obj = ParseValue(charArray, ref index, ref success);
}
else
obj = null;
return success;
}
public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
{
object jsonObject = DeserializeObject(json);
return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)
? jsonObject
: (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);
}
public static object DeserializeObject(string json, Type type)
{
return DeserializeObject(json, type, null);
}
public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)
{
return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
}
public static T DeserializeObject<T>(string json)
{
return (T)DeserializeObject(json, typeof(T), null);
}
/// <summary>
/// Converts a IDictionary<string,object> / IList<object> object into a JSON string
/// </summary>
/// <param name="json">A IDictionary<string,object> / IList<object></param>
/// <param name="jsonSerializerStrategy">Serializer strategy to use</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
{
StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
bool success = SerializeValue(jsonSerializerStrategy, json, builder);
return (success ? builder.ToString() : null);
}
public static string SerializeObject(object json)
{
return SerializeObject(json, CurrentJsonSerializerStrategy);
}
public static string EscapeToJavascriptString(string jsonString)
{
if (string.IsNullOrEmpty(jsonString))
return jsonString;
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < jsonString.Length; )
{
c = jsonString[i++];
if (c == '\\')
{
int remainingLength = jsonString.Length - i;
if (remainingLength >= 2)
{
char lookahead = jsonString[i];
if (lookahead == '\\')
{
sb.Append('\\');
++i;
}
else if (lookahead == '"')
{
sb.Append("\"");
++i;
}
else if (lookahead == 't')
{
sb.Append('\t');
++i;
}
else if (lookahead == 'b')
{
sb.Append('\b');
++i;
}
else if (lookahead == 'n')
{
sb.Append('\n');
++i;
}
else if (lookahead == 'r')
{
sb.Append('\r');
++i;
}
}
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
{
IDictionary<string, object> table = new JsonObject();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done)
{
token = LookAhead(json, index);
if (token == TOKEN_NONE)
{
success = false;
return null;
}
else if (token == TOKEN_COMMA)
NextToken(json, ref index);
else if (token == TOKEN_CURLY_CLOSE)
{
NextToken(json, ref index);
return table;
}
else
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != TOKEN_COLON)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
static JsonArray ParseArray(char[] json, ref int index, ref bool success)
{
JsonArray array = new JsonArray();
// [
NextToken(json, ref index);
bool done = false;
while (!done)
{
int token = LookAhead(json, index);
if (token == TOKEN_NONE)
{
success = false;
return null;
}
else if (token == TOKEN_COMMA)
NextToken(json, ref index);
else if (token == TOKEN_SQUARED_CLOSE)
{
NextToken(json, ref index);
break;
}
else
{
object value = ParseValue(json, ref index, ref success);
if (!success)
return null;
array.Add(value);
}
}
return array;
}
static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index))
{
case TOKEN_STRING:
return ParseString(json, ref index, ref success);
case TOKEN_NUMBER:
return ParseNumber(json, ref index, ref success);
case TOKEN_CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case TOKEN_SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case TOKEN_TRUE:
NextToken(json, ref index);
return true;
case TOKEN_FALSE:
NextToken(json, ref index);
return false;
case TOKEN_NULL:
NextToken(json, ref index);
return null;
case TOKEN_NONE:
break;
}
success = false;
return null;
}
static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
char c;
EatWhitespace(json, ref index);
// "
c = json[index++];
bool complete = false;
while (!complete)
{
if (index == json.Length)
break;
c = json[index++];
if (c == '"')
{
complete = true;
break;
}
else if (c == '\\')
{
if (index == json.Length)
break;
c = json[index++];
if (c == '"')
s.Append('"');
else if (c == '\\')
s.Append('\\');
else if (c == '/')
s.Append('/');
else if (c == 'b')
s.Append('\b');
else if (c == 'f')
s.Append('\f');
else if (c == 'n')
s.Append('\n');
else if (c == 'r')
s.Append('\r');
else if (c == 't')
s.Append('\t');
else if (c == 'u')
{
int remainingLength = json.Length - index;
if (remainingLength >= 4)
{
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
return "";
// convert the integer codepoint to a unicode char and add to string
if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate
{
index += 4; // skip 4 chars
remainingLength = json.Length - index;
if (remainingLength >= 6)
{
uint lowCodePoint;
if (new string(json, index, 2) == "\\u" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))
{
if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate
{
s.Append((char)codePoint);
s.Append((char)lowCodePoint);
index += 6; // skip 6 chars
continue;
}
}
}
success = false; // invalid surrogate pair
return "";
}
s.Append(ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
else
break;
}
}
else
s.Append(c);
}
if (!complete)
{
success = false;
return null;
}
return s.ToString();
}
private static string ConvertFromUtf32(int utf32)
{
// http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm
if (utf32 < 0 || utf32 > 0x10FFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
if (0xD800 <= utf32 && utf32 <= 0xDFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
if (utf32 < 0x10000)
return new string((char)utf32, 1);
utf32 -= 0x10000;
return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });
}
static object ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
object returnNumber;
string str = new string(json, index, charLength);
if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
{
double number;
success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
}
else
{
long number;
success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
}
index = lastIndex + 1;
return returnNumber;
}
static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++)
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
return lastIndex - 1;
}
static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++)
if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
}
static int LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
static int NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length)
return TOKEN_NONE;
char c = json[index];
index++;
switch (c)
{
case '{':
return TOKEN_CURLY_OPEN;
case '}':
return TOKEN_CURLY_CLOSE;
case '[':
return TOKEN_SQUARED_OPEN;
case ']':
return TOKEN_SQUARED_CLOSE;
case ',':
return TOKEN_COMMA;
case '"':
return TOKEN_STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN_NUMBER;
case ':':
return TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
{
index += 5;
return TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
{
index += 4;
return TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
{
index += 4;