forked from toptensoftware/JsonKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PetaJson.cs
executable file
·3425 lines (3009 loc) · 135 KB
/
PetaJson.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
// PetaJson v0.5 - A simple but flexible Json library in a single .cs file.
//
// Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
// Define PETAJSON_NO_DYNAMIC to disable Expando support
// Define PETAJSON_NO_EMIT to disable Reflection.Emit
// Define PETAJSON_NO_DATACONTRACT to disable support for [DataContract]/[DataMember]
// Define PETAJSON_PORTABLE to enable usage of TypeInfo instead of Type for Reflection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Collections;
using System.Threading;
#if !PETAJSON_NO_DYNAMIC
using System.Dynamic;
#endif
#if !PETAJSON_NO_EMIT
using System.Reflection.Emit;
#endif
#if !PETAJSON_NO_DATACONTRACT
using System.Runtime.Serialization;
#endif
#if PETAJSON_PORTABLE
using System.Diagnostics;
#endif
namespace PetaJson
{
// Pass to format/write/parse functions to override defaults
[Flags]
public enum JsonOptions
{
None = 0,
WriteWhitespace = 0x00000001,
DontWriteWhitespace = 0x00000002,
StrictParser = 0x00000004,
NonStrictParser = 0x00000008,
}
// API
public static class Json
{
static Json()
{
WriteWhitespaceDefault = true;
StrictParserDefault = false;
#if !PETAJSON_NO_EMIT
Json.SetFormatterResolver(Internal.Emit.MakeFormatter);
Json.SetParserResolver(Internal.Emit.MakeParser);
Json.SetIntoParserResolver(Internal.Emit.MakeIntoParser);
#endif
}
// Pretty format default
public static bool WriteWhitespaceDefault
{
get;
set;
}
// Strict parser
public static bool StrictParserDefault
{
get;
set;
}
// Write an object to a text writer
public static void Write(TextWriter w, object o, JsonOptions options = JsonOptions.None)
{
var writer = new Internal.Writer(w, ResolveOptions(options));
writer.WriteValue(o);
}
#if !PETAJSON_PORTABLE
// Write an object to a file
public static void WriteFile(string filename, object o, JsonOptions options = JsonOptions.None)
{
using (var w = new StreamWriter(filename))
{
Write(w, o, options);
}
}
#endif
// Format an object as a json string
public static string Format(object o, JsonOptions options = JsonOptions.None)
{
var sw = new StringWriter();
var writer = new Internal.Writer(sw, ResolveOptions(options));
writer.WriteValue(o);
return sw.ToString();
}
// Parse an object of specified type from a text reader
public static object Parse(TextReader r, Type type, JsonOptions options = JsonOptions.None)
{
Internal.Reader reader = null;
try
{
reader = new Internal.Reader(r, ResolveOptions(options));
var retv = reader.Parse(type);
reader.CheckEOF();
return retv;
}
catch (Exception x)
{
var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
#if PETAJSON_PORTABLE
Debug.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
#else
Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
#endif
throw new JsonParseException(x, reader.Context, loc);
}
}
// Parse an object of specified type from a text reader
public static T Parse<T>(TextReader r, JsonOptions options = JsonOptions.None)
{
return (T)Parse(r, typeof(T), options);
}
// Parse from text reader into an already instantied object
public static void ParseInto(TextReader r, Object into, JsonOptions options = JsonOptions.None)
{
if (into == null)
throw new NullReferenceException();
#if PETAJSON_PORTABLE
if (into.GetType().GetTypeInfo().IsValueType)
throw new InvalidOperationException("Can't ParseInto a value type");
#else
if (into.GetType().IsValueType)
throw new InvalidOperationException("Can't ParseInto a value type");
#endif
Internal.Reader reader = null;
try
{
reader = new Internal.Reader(r, ResolveOptions(options));
reader.ParseInto(into);
reader.CheckEOF();
}
catch (Exception x)
{
var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
#if PETAJSON_PORTABLE
Debug.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
#else
Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
#endif
throw new JsonParseException(x, reader.Context, loc);
}
}
#if !PETAJSON_PORTABLE
// Parse an object of specified type from a file
public static object ParseFile(string filename, Type type, JsonOptions options = JsonOptions.None)
{
using (var r = new StreamReader(filename))
{
return Parse(r, type, options);
}
}
// Parse an object of specified type from a file
public static T ParseFile<T>(string filename, JsonOptions options = JsonOptions.None)
{
using (var r = new StreamReader(filename))
{
return Parse<T>(r, options);
}
}
// Parse from file into an already instantied object
public static void ParseFileInto(string filename, Object into, JsonOptions options = JsonOptions.None)
{
using (var r = new StreamReader(filename))
{
ParseInto(r, into, options);
}
}
#endif
// Parse an object from a string
public static object Parse(string data, Type type, JsonOptions options = JsonOptions.None)
{
return Parse(new StringReader(data), type, options);
}
// Parse an object from a string
public static T Parse<T>(string data, JsonOptions options = JsonOptions.None)
{
return (T)Parse<T>(new StringReader(data), options);
}
// Parse from string into an already instantiated object
public static void ParseInto(string data, Object into, JsonOptions options = JsonOptions.None)
{
ParseInto(new StringReader(data), into, options);
}
// Create a clone of an object
public static T Clone<T>(T source)
{
return (T)Reparse(source.GetType(), source);
}
// Create a clone of an object (untyped)
public static object Clone(object source)
{
return Reparse(source.GetType(), source);
}
// Clone an object into another instance
public static void CloneInto(object dest, object source)
{
ReparseInto(dest, source);
}
// Reparse an object by writing to a stream and re-reading (possibly
// as a different type).
public static object Reparse(Type type, object source)
{
if (source == null)
return null;
var ms = new MemoryStream();
try
{
// Write
var w = new StreamWriter(ms);
Json.Write(w, source);
w.Flush();
// Read
ms.Seek(0, SeekOrigin.Begin);
var r = new StreamReader(ms);
return Json.Parse(r, type);
}
finally
{
ms.Dispose();
}
}
// Typed version of above
public static T Reparse<T>(object source)
{
return (T)Reparse(typeof(T), source);
}
// Reparse one object into another object
public static void ReparseInto(object dest, object source)
{
var ms = new MemoryStream();
try
{
// Write
var w = new StreamWriter(ms);
Json.Write(w, source);
w.Flush();
// Read
ms.Seek(0, SeekOrigin.Begin);
var r = new StreamReader(ms);
Json.ParseInto(r, dest);
}
finally
{
ms.Dispose();
}
}
// Register a callback that can format a value of a particular type into json
public static void RegisterFormatter(Type type, Action<IJsonWriter, object> formatter)
{
Internal.Writer._formatters[type] = formatter;
}
// Typed version of above
public static void RegisterFormatter<T>(Action<IJsonWriter, T> formatter)
{
RegisterFormatter(typeof(T), (w, o) => formatter(w, (T)o));
}
// Register a parser for a specified type
public static void RegisterParser(Type type, Func<IJsonReader, Type, object> parser)
{
Internal.Reader._parsers.Set(type, parser);
}
// Register a typed parser
public static void RegisterParser<T>(Func<IJsonReader, Type, T> parser)
{
RegisterParser(typeof(T), (r, t) => parser(r, t));
}
// Simpler version for simple types
public static void RegisterParser(Type type, Func<object, object> parser)
{
RegisterParser(type, (r, t) => r.ReadLiteral(parser));
}
// Simpler and typesafe parser for simple types
public static void RegisterParser<T>(Func<object, T> parser)
{
RegisterParser(typeof(T), literal => parser(literal));
}
// Register an into parser
public static void RegisterIntoParser(Type type, Action<IJsonReader, object> parser)
{
Internal.Reader._intoParsers.Set(type, parser);
}
// Register an into parser
public static void RegisterIntoParser<T>(Action<IJsonReader, object> parser)
{
RegisterIntoParser(typeof(T), parser);
}
// Register a factory for instantiating objects (typically abstract classes)
// Callback will be invoked for each key in the dictionary until it returns an object
// instance and which point it will switch to serialization using reflection
public static void RegisterTypeFactory(Type type, Func<IJsonReader, string, object> factory)
{
Internal.Reader._typeFactories.Set(type, factory);
}
// Register a callback to provide a formatter for a newly encountered type
public static void SetFormatterResolver(Func<Type, Action<IJsonWriter, object>> resolver)
{
Internal.Writer._formatterResolver = resolver;
}
// Register a callback to provide a parser for a newly encountered value type
public static void SetParserResolver(Func<Type, Func<IJsonReader, Type, object>> resolver)
{
Internal.Reader._parserResolver = resolver;
}
// Register a callback to provide a parser for a newly encountered reference type
public static void SetIntoParserResolver(Func<Type, Action<IJsonReader, object>> resolver)
{
Internal.Reader._intoParserResolver = resolver;
}
public static bool WalkPath(this IDictionary<string, object> This, string Path, bool create, Func<IDictionary<string, object>, string, bool> leafCallback)
{
// Walk the path
var parts = Path.Split('.');
for (int i = 0; i < parts.Length - 1; i++)
{
object val;
if (!This.TryGetValue(parts[i], out val))
{
if (!create)
return false;
val = new Dictionary<string, object>();
This[parts[i]] = val;
}
This = (IDictionary<string, object>)val;
}
// Process the leaf
return leafCallback(This, parts[parts.Length - 1]);
}
public static bool PathExists(this IDictionary<string, object> This, string Path)
{
return This.WalkPath(Path, false, (dict, key) => dict.ContainsKey(key));
}
public static object GetPath(this IDictionary<string, object> This, Type type, string Path, object def)
{
This.WalkPath(Path, false, (dict, key) =>
{
object val;
if (dict.TryGetValue(key, out val))
{
if (val == null)
def = val;
#if PETAJSON_PORTABLE
else if(type.GetTypeInfo().IsAssignableFrom(val.GetType().GetTypeInfo()))
#else
else if (type.IsAssignableFrom(val.GetType()))
#endif
def = val;
else
def = Reparse(type, val);
}
return true;
});
return def;
}
// Ensure there's an object of type T at specified path
public static T GetObjectAtPath<T>(this IDictionary<string, object> This, string Path) where T : class,new()
{
T retVal = null;
This.WalkPath(Path, true, (dict, key) =>
{
object val;
dict.TryGetValue(key, out val);
retVal = val as T;
if (retVal == null)
{
retVal = val == null ? new T() : Reparse<T>(val);
dict[key] = retVal;
}
return true;
});
return retVal;
}
public static T GetPath<T>(this IDictionary<string, object> This, string Path, T def = default(T))
{
return (T)This.GetPath(typeof(T), Path, def);
}
public static void SetPath(this IDictionary<string, object> This, string Path, object value)
{
This.WalkPath(Path, true, (dict, key) => { dict[key] = value; return true; });
}
// Resolve passed options
static JsonOptions ResolveOptions(JsonOptions options)
{
JsonOptions resolved = JsonOptions.None;
if ((options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace)) != 0)
resolved |= options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace);
else
resolved |= WriteWhitespaceDefault ? JsonOptions.WriteWhitespace : JsonOptions.DontWriteWhitespace;
if ((options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser)) != 0)
resolved |= options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser);
else
resolved |= StrictParserDefault ? JsonOptions.StrictParser : JsonOptions.NonStrictParser;
return resolved;
}
}
// Called before loading via reflection
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonLoading
{
void OnJsonLoading(IJsonReader r);
}
// Called after loading via reflection
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonLoaded
{
void OnJsonLoaded(IJsonReader r);
}
// Called for each field while loading from reflection
// Return true if handled
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonLoadField
{
bool OnJsonField(IJsonReader r, string key);
}
// Called when about to write using reflection
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonWriting
{
void OnJsonWriting(IJsonWriter w);
}
// Called after written using reflection
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonWritten
{
void OnJsonWritten(IJsonWriter w);
}
// Describes the current literal in the json stream
public enum LiteralKind
{
None,
String,
Null,
True,
False,
SignedInteger,
UnsignedInteger,
FloatingPoint,
}
// Passed to registered parsers
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonReader
{
object Parse(Type type);
T Parse<T>();
void ParseInto(object into);
object ReadLiteral(Func<object, object> converter);
void ParseDictionary(Action<string> callback);
void ParseArray(Action callback);
LiteralKind GetLiteralKind();
string GetLiteralString();
void NextToken();
}
// Passed to registered formatters
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public interface IJsonWriter
{
void WriteStringLiteral(string str);
void WriteRaw(string str);
void WriteArray(Action callback);
void WriteDictionary(Action callback);
void WriteValue(object value);
void WriteElement();
void WriteKey(string key);
void WriteKeyNoEscaping(string key);
}
// Exception thrown for any parse error
public class JsonParseException : Exception
{
public JsonParseException(Exception inner, string context, JsonLineOffset position) :
base(string.Format("JSON parse error at {0}{1} - {2}", position, string.IsNullOrEmpty(context) ? "" : string.Format(", context {0}", context), inner.Message), inner)
{
Position = position;
Context = context;
}
public JsonLineOffset Position;
public string Context;
}
// Represents a line and character offset position in the source Json
public struct JsonLineOffset
{
public int Line;
public int Offset;
public override string ToString()
{
return string.Format("line {0}, character {1}", Line + 1, Offset + 1);
}
}
// Used to decorate fields and properties that should be serialized
//
// - [Json] on class or struct causes all public fields and properties to be serialized
// - [Json] on a public or non-public field or property causes that member to be serialized
// - [JsonExclude] on a field or property causes that field to be not serialized
// - A class or struct with no [Json] attribute has all public fields/properties serialized
// - A class or struct with no [Json] attribute but a [Json] attribute on one or more members only serializes those members
//
// Use [Json("keyname")] to explicitly specify the key to be used
// [Json] without the keyname will be serialized using the name of the member with the first letter lowercased.
//
// [Json(KeepInstance=true)] causes container/subobject types to be serialized into the existing member instance (if not null)
//
// You can also use the system supplied DataContract and DataMember attributes. They'll only be used if there
// are no PetaJson attributes on the class or it's members. You must specify DataContract on the type and
// DataMember on any fields/properties that require serialization. There's no need for exclude attribute.
// When using DataMember, the name of the field or property is used as is - the first letter is left in upper case
//
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)]
public class JsonAttribute : Attribute
{
public JsonAttribute()
{
_key = null;
}
public JsonAttribute(string key)
{
_key = key;
}
// Key used to save this field/property
string _key;
public string Key
{
get { return _key; }
}
// If true uses ParseInto to parse into the existing object instance
// If false, creates a new instance as assigns it to the property
public bool KeepInstance
{
get;
set;
}
// If true, the property will be loaded, but not saved
// Use to upgrade deprecated persisted settings, but not
// write them back out again
public bool Deprecated
{
get;
set;
}
}
// See comments for JsonAttribute above
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class JsonExcludeAttribute : Attribute
{
public JsonExcludeAttribute()
{
}
}
namespace Internal
{
#if !PETAJSON_PORTABLE
[Obfuscation(Exclude = true, ApplyToMembers = true)]
#endif
public enum Token
{
EOF,
Identifier,
Literal,
OpenBrace,
CloseBrace,
OpenSquare,
CloseSquare,
Equal,
Colon,
SemiColon,
Comma,
}
// Helper to create instances but include the type name in the thrown exception
public static class DecoratingActivator
{
public static object CreateInstance(Type t)
{
try
{
return Activator.CreateInstance(t);
}
catch (Exception x)
{
throw new InvalidOperationException(string.Format("Failed to create instance of type '{0}'", t.FullName), x);
}
}
}
public class Reader : IJsonReader
{
static Reader()
{
// Setup default resolvers
_parserResolver = ResolveParser;
_intoParserResolver = ResolveIntoParser;
Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
{
return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
};
Func<IJsonReader, Type, object> numberConverter = (reader, type) =>
{
switch (reader.GetLiteralKind())
{
case LiteralKind.SignedInteger:
case LiteralKind.UnsignedInteger:
case LiteralKind.FloatingPoint:
object val = Convert.ChangeType(reader.GetLiteralString(), type, CultureInfo.InvariantCulture);
reader.NextToken();
return val;
}
throw new InvalidDataException("expected a numeric literal");
};
// Default type handlers
_parsers.Set(typeof(string), simpleConverter);
_parsers.Set(typeof(char), simpleConverter);
_parsers.Set(typeof(bool), simpleConverter);
_parsers.Set(typeof(byte), numberConverter);
_parsers.Set(typeof(sbyte), numberConverter);
_parsers.Set(typeof(short), numberConverter);
_parsers.Set(typeof(ushort), numberConverter);
_parsers.Set(typeof(int), numberConverter);
_parsers.Set(typeof(uint), numberConverter);
_parsers.Set(typeof(long), numberConverter);
_parsers.Set(typeof(ulong), numberConverter);
_parsers.Set(typeof(decimal), numberConverter);
_parsers.Set(typeof(float), numberConverter);
_parsers.Set(typeof(double), numberConverter);
_parsers.Set(typeof(DateTime), (reader, type) =>
{
return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
});
_parsers.Set(typeof(byte[]), (reader, type) =>
{
return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
});
}
public Reader(TextReader r, JsonOptions options)
{
_tokenizer = new Tokenizer(r, options);
_options = options;
}
Tokenizer _tokenizer;
JsonOptions _options;
List<string> _contextStack = new List<string>();
public string Context
{
get
{
return string.Join(".", _contextStack);
}
}
static Action<IJsonReader, object> ResolveIntoParser(Type type)
{
var ri = ReflectionInfo.GetReflectionInfo(type);
if (ri != null)
return ri.ParseInto;
else
return null;
}
static Func<IJsonReader, Type, object> ResolveParser(Type type)
{
// See if the Type has a static parser method - T ParseJson(IJsonReader)
var parseJson = ReflectionInfo.FindParseJson(type);
if (parseJson != null)
{
if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
{
return (r, t) => parseJson.Invoke(null, new Object[] { r });
}
else
{
return (r, t) =>
{
if (r.GetLiteralKind() == LiteralKind.String)
{
var o = parseJson.Invoke(null, new Object[] { r.GetLiteralString() });
r.NextToken();
return o;
}
throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
};
}
}
return (r, t) =>
{
var into = DecoratingActivator.CreateInstance(type);
r.ParseInto(into);
return into;
};
}
public JsonLineOffset CurrentTokenPosition
{
get { return _tokenizer.CurrentTokenPosition; }
}
// ReadLiteral is implemented with a converter callback so that any
// errors on converting to the target type are thrown before the tokenizer
// is advanced to the next token. This ensures error location is reported
// at the start of the literal, not the following token.
public object ReadLiteral(Func<object, object> converter)
{
_tokenizer.Check(Token.Literal);
var retv = converter(_tokenizer.LiteralValue);
_tokenizer.NextToken();
return retv;
}
public void CheckEOF()
{
_tokenizer.Check(Token.EOF);
}
public object Parse(Type type)
{
// Null?
if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
{
_tokenizer.NextToken();
return null;
}
// Handle nullable types
var typeUnderlying = Nullable.GetUnderlyingType(type);
if (typeUnderlying != null)
type = typeUnderlying;
// See if we have a reader
Func<IJsonReader, Type, object> parser;
if (Reader._parsers.TryGetValue(type, out parser))
{
return parser(this, type);
}
// See if we have factory
Func<IJsonReader, string, object> factory;
if (Reader._typeFactories.TryGetValue(type, out factory))
{
// Try first without passing dictionary keys
object into = factory(this, null);
if (into == null)
{
// This is a awkward situation. The factory requires a value from the dictionary
// in order to create the target object (typically an abstract class with the class
// kind recorded in the Json). Since there's no guarantee of order in a json dictionary
// we can't assume the required key is first.
// So, create a bookmark on the tokenizer, read keys until the factory returns an
// object instance and then rewind the tokenizer and continue
// Create a bookmark so we can rewind
_tokenizer.CreateBookmark();
// Skip the opening brace
_tokenizer.Skip(Token.OpenBrace);
// First pass to work out type
ParseDictionaryKeys(key =>
{
// Try to instantiate the object
into = factory(this, key);
return into == null;
});
// Move back to start of the dictionary
_tokenizer.RewindToBookmark();
// Quit if still didn't get an object from the factory
if (into == null)
throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
}
// Second pass
ParseInto(into);
// Done
return into;
}
// Do we already have an into parser?
Action<IJsonReader, object> intoParser;
if (Reader._intoParsers.TryGetValue(type, out intoParser))
{
var into = DecoratingActivator.CreateInstance(type);
ParseInto(into);
return into;
}
// Enumerated type?
#if PETAJSON_PORTABLE
TypeInfo typeInfo = type.GetTypeInfo();
if(typeInfo.IsEnum)
{
if(typeInfo.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
#else
if (type.IsEnum)
{
if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
#endif
return ReadLiteral(literal =>
{
try
{
return Enum.Parse(type, (string)literal);
}
catch
{
return Enum.ToObject(type, literal);
}
});
else
return ReadLiteral(literal => Enum.Parse(type, (string)literal));
}
// Array?
if (type.IsArray && type.GetArrayRank() == 1)
{
// First parse as a List<>
var listType = typeof(List<>).MakeGenericType(type.GetElementType());
var list = DecoratingActivator.CreateInstance(listType);
ParseInto(list);
#if PETAJSON_PORTABLE
return listType.GetTypeInfo().GetDeclaredMethod("ToArray").Invoke(list, null);
#else
return listType.GetMethod("ToArray").Invoke(list, null);
#endif
}
// Convert interfaces to concrete types
#if PETAJSON_PORTABLE
if (typeInfo.IsInterface)
{
type = Utils.ResolveInterfaceToClass(type);
typeInfo = type.GetTypeInfo();
}
// Untyped dictionary?
if (_tokenizer.CurrentToken == Token.OpenBrace && (typeInfo.IsAssignableFrom(typeof(IDictionary<string, object>).GetTypeInfo())))
#else
if (type.IsInterface)
type = Utils.ResolveInterfaceToClass(type);
// Untyped dictionary?
if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(IDictionary<string, object>))))
#endif
{
#if !PETAJSON_NO_DYNAMIC
var container = (new ExpandoObject()) as IDictionary<string, object>;
#else
var container = new Dictionary<string, object>();
#endif
ParseDictionary(key =>
{
container[key] = Parse(typeof(Object));
});
return container;
}
#if PETAJSON_PORTABLE
if (_tokenizer.CurrentToken == Token.OpenSquare && (typeInfo.IsAssignableFrom(typeof(List<object>).GetTypeInfo())))
#else
// Untyped list?
if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
#endif
{
var container = new List<object>();
ParseArray(() =>
{
container.Add(Parse(typeof(Object)));
});
return container;
}
#if PETAJSON_PORTABLE
if (_tokenizer.CurrentToken == Token.Literal && typeInfo.IsAssignableFrom(_tokenizer.LiteralType.GetTypeInfo()))
#else
// Untyped literal?
if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.LiteralType))
#endif
{
var lit = _tokenizer.LiteralValue;
_tokenizer.NextToken();
return lit;
}
#if PETAJSON_PORTABLE
if(typeInfo.IsValueType)
#else
// Call value type resolver
if (type.IsValueType)
#endif
{
var tp = _parsers.Get(type, () => _parserResolver(type));
if (tp != null)
{