-
Notifications
You must be signed in to change notification settings - Fork 170
/
JsonSerializerInternalReader.cs
2616 lines (2269 loc) · 116 KB
/
JsonSerializerInternalReader.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
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
#if !(NET35 || NET20 || PORTABLE40)
using System.ComponentModel;
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalReader : JsonSerializerInternalBase
{
internal enum PropertyPresence
{
None = 0,
Null = 1,
Value = 2
}
public JsonSerializerInternalReader(JsonSerializer serializer)
: base(serializer)
{
}
public void Populate(JsonReader reader, object target)
{
ValidationUtils.ArgumentNotNull(target, nameof(target));
Type objectType = target.GetType();
JsonContract contract = Serializer._contractResolver.ResolveContract(objectType);
if (!reader.MoveToContent())
{
throw JsonSerializationException.Create(reader, "No JSON content found.");
}
if (reader.TokenType == JsonToken.StartArray)
{
if (contract.ContractType == JsonContractType.Array)
{
JsonArrayContract arrayContract = (JsonArrayContract)contract;
PopulateList((arrayContract.ShouldCreateWrapper) ? arrayContract.CreateWrapper(target) : (IList)target, reader, arrayContract, null, null);
}
else
{
throw JsonSerializationException.Create(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
}
else if (reader.TokenType == JsonToken.StartObject)
{
reader.ReadAndAssert();
string id = null;
if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore
&& reader.TokenType == JsonToken.PropertyName
&& string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
{
reader.ReadAndAssert();
id = (reader.Value != null) ? reader.Value.ToString() : null;
reader.ReadAndAssert();
}
if (contract.ContractType == JsonContractType.Dictionary)
{
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract;
PopulateDictionary((dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(target) : (IDictionary)target, reader, dictionaryContract, null, id);
}
else if (contract.ContractType == JsonContractType.Object)
{
PopulateObject(target, reader, (JsonObjectContract)contract, null, id);
}
else
{
throw JsonSerializationException.Create(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private JsonContract GetContractSafe(Type type)
{
if (type == null)
{
return null;
}
return Serializer._contractResolver.ResolveContract(type);
}
public object Deserialize(JsonReader reader, Type objectType, bool checkAdditionalContent)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
JsonContract contract = GetContractSafe(objectType);
try
{
JsonConverter converter = GetConverter(contract, null, null, null);
if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null))
{
if (contract != null && !contract.IsNullable)
{
throw JsonSerializationException.Create(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
return null;
}
object deserializedValue;
if (converter != null && converter.CanRead)
{
deserializedValue = DeserializeConvertable(converter, reader, objectType, null);
}
else
{
deserializedValue = CreateValueInternal(reader, objectType, contract, null, null, null, null);
}
if (checkAdditionalContent)
{
if (reader.Read() && reader.TokenType != JsonToken.Comment)
{
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
return deserializedValue;
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, reader as IJsonLineInfo, reader.Path, ex))
{
HandleError(reader, false, 0);
return null;
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (InternalSerializer == null)
{
InternalSerializer = new JsonSerializerProxy(this);
}
return InternalSerializer;
}
#if !NO_JSONLINQ
private JToken CreateJToken(JsonReader reader, JsonContract contract)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
if (contract != null)
{
if (contract.UnderlyingType == typeof(JRaw))
{
return JRaw.Create(reader);
}
if (reader.TokenType == JsonToken.Null
&& !(contract.UnderlyingType == typeof(JValue) || contract.UnderlyingType == typeof(JToken)))
{
return null;
}
}
JToken token;
using (JTokenWriter writer = new JTokenWriter())
{
writer.WriteToken(reader);
token = writer.Token;
}
return token;
}
private JToken CreateJObject(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
// this is needed because we've already read inside the object, looking for metadata properties
using (JTokenWriter writer = new JTokenWriter())
{
writer.WriteStartObject();
do
{
if (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = (string)reader.Value;
if (!reader.ReadAndMoveToContent())
{
break;
}
if (CheckPropertyName(reader, propertyName))
{
continue;
}
writer.WritePropertyName(propertyName);
writer.WriteToken(reader, true, true, false);
}
else if (reader.TokenType == JsonToken.Comment)
{
// eat
}
else
{
writer.WriteEndObject();
return writer.Token;
}
} while (reader.Read());
throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
}
}
#endif
private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue)
{
#if !NO_JSONLINQ
if (contract != null && contract.ContractType == JsonContractType.Linq)
{
return CreateJToken(reader, contract);
}
#endif
do
{
switch (reader.TokenType)
{
// populate a typed object or generic dictionary/array
// depending upon whether an objectType was supplied
case JsonToken.StartObject:
return CreateObject(reader, objectType, contract, member, containerContract, containerMember, existingValue);
case JsonToken.StartArray:
return CreateList(reader, objectType, contract, member, existingValue, null);
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
case JsonToken.String:
string s = (string)reader.Value;
// convert empty string to null automatically for nullable types
if (CoerceEmptyStringToNull(objectType, contract, s))
{
return null;
}
// string that needs to be returned as a byte array should be base 64 decoded
if (objectType == typeof(byte[]))
{
return Convert.FromBase64String(s);
}
return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType);
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType);
case JsonToken.Null:
case JsonToken.Undefined:
#if !(DOTNET || PORTABLE40 || PORTABLE)
if (objectType == typeof(DBNull))
{
return DBNull.Value;
}
#endif
return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType);
#if !NO_JSONLINQ
case JsonToken.Raw:
return new JRaw((string)reader.Value);
#endif
case JsonToken.Comment:
// ignore
break;
default:
throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType);
}
} while (reader.Read());
throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
}
private static bool CoerceEmptyStringToNull(Type objectType, JsonContract contract, string s)
{
return string.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable;
}
internal string GetExpectedDescription(JsonContract contract)
{
switch (contract.ContractType)
{
case JsonContractType.Object:
case JsonContractType.Dictionary:
#if !(DOTNET || PORTABLE || PORTABLE40)
case JsonContractType.Serializable:
#endif
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
#endif
return @"JSON object (e.g. {""name"":""value""})";
case JsonContractType.Array:
return @"JSON array (e.g. [1,2,3])";
case JsonContractType.Primitive:
return @"JSON primitive value (e.g. string, number, boolean, null)";
case JsonContractType.String:
return @"JSON string value";
default:
throw new ArgumentOutOfRangeException();
}
}
private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty)
{
JsonConverter converter = null;
if (memberConverter != null)
{
// member attribute converter
converter = memberConverter;
}
else if (containerProperty != null && containerProperty.ItemConverter != null)
{
converter = containerProperty.ItemConverter;
}
else if (containerContract != null && containerContract.ItemConverter != null)
{
converter = containerContract.ItemConverter;
}
else if (contract != null)
{
JsonConverter matchingConverter;
if (contract.Converter != null)
{
// class attribute converter
converter = contract.Converter;
}
else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null)
{
// passed in converters
converter = matchingConverter;
}
else if (contract.InternalConverter != null)
{
// internally specified converter
converter = contract.InternalConverter;
}
}
return converter;
}
private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue)
{
string id;
Type resolvedObjectType = objectType;
if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.Ignore)
{
// don't look for metadata properties
reader.ReadAndAssert();
id = null;
}
else if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.ReadAhead)
{
#if NO_JSONLINQ
id = null;
#else
JTokenReader tokenReader = reader as JTokenReader;
if (tokenReader == null)
{
JToken t = JToken.ReadFrom(reader);
tokenReader = (JTokenReader)t.CreateReader();
tokenReader.Culture = reader.Culture;
tokenReader.DateFormatString = reader.DateFormatString;
tokenReader.DateParseHandling = reader.DateParseHandling;
tokenReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
tokenReader.FloatParseHandling = reader.FloatParseHandling;
tokenReader.SupportMultipleContent = reader.SupportMultipleContent;
// start
tokenReader.ReadAndAssert();
reader = tokenReader;
}
object newValue;
if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id))
{
return newValue;
}
#endif
}
else
{
reader.ReadAndAssert();
object newValue;
if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out newValue, out id))
{
return newValue;
}
}
if (HasNoDefinedType(contract))
{
#if NO_JSONLINQ
return null;
#else
return CreateJObject(reader);
#endif
}
switch (contract.ContractType)
{
case JsonContractType.Object:
{
bool createdFromNonDefaultCreator = false;
JsonObjectContract objectContract = (JsonObjectContract)contract;
object targetObject;
// check that if type name handling is being used that the existing value is compatible with the specified type
if (existingValue != null && (resolvedObjectType == objectType || resolvedObjectType.IsAssignableFrom(existingValue.GetType())))
{
targetObject = existingValue;
}
else
{
targetObject = CreateNewObject(reader, objectContract, member, containerMember, id, out createdFromNonDefaultCreator);
}
// don't populate if read from non-default creator because the object has already been read
if (createdFromNonDefaultCreator)
{
return targetObject;
}
return PopulateObject(targetObject, reader, objectContract, member, id);
}
case JsonContractType.Primitive:
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
// if the content is inside $value then read past it
if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore
&& reader.TokenType == JsonToken.PropertyName
&& string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal))
{
reader.ReadAndAssert();
// the token should not be an object because the $type value could have been included in the object
// without needing the $value property
if (reader.TokenType == JsonToken.StartObject)
{
throw JsonSerializationException.Create(reader, "Unexpected token when deserializing primitive value: " + reader.TokenType);
}
object value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue);
reader.ReadAndAssert();
return value;
}
break;
}
case JsonContractType.Dictionary:
{
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)contract;
object targetDictionary;
if (existingValue == null)
{
bool createdFromNonDefaultCreator;
IDictionary dictionary = CreateNewDictionary(reader, dictionaryContract, out createdFromNonDefaultCreator);
if (createdFromNonDefaultCreator)
{
if (id != null)
{
throw JsonSerializationException.Create(reader, "Cannot preserve reference to readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
if (contract.OnSerializingCallbacks.Count > 0)
{
throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on readonly dictionary, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
if (contract.OnErrorCallbacks.Count > 0)
{
throw JsonSerializationException.Create(reader, "Cannot call OnError on readonly list, or dictionary created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
if (!dictionaryContract.HasParameterizedCreatorInternal)
{
throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size dictionary: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
}
PopulateDictionary(dictionary, reader, dictionaryContract, member, id);
if (createdFromNonDefaultCreator)
{
ObjectConstructor<object> creator = dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator;
return creator(dictionary);
}
else if (dictionary is IWrappedDictionary)
{
return ((IWrappedDictionary)dictionary).UnderlyingDictionary;
}
targetDictionary = dictionary;
}
else
{
targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id);
}
return targetDictionary;
}
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
JsonDynamicContract dynamicContract = (JsonDynamicContract)contract;
return CreateDynamic(reader, dynamicContract, member, id);
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
#if !NO_JSONLINQ
case JsonContractType.Serializable:
JsonISerializableContract serializableContract = (JsonISerializableContract)contract;
return CreateISerializable(reader, serializableContract, member, id);
#endif
#endif
}
string message = @"Cannot deserialize the current JSON object (e.g. {{""name"":""value""}}) into type '{0}' because the type requires a {1} to deserialize correctly." + Environment.NewLine +
@"To fix this error either change the JSON to a {1} or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, resolvedObjectType, GetExpectedDescription(contract));
throw JsonSerializationException.Create(reader, message);
}
#if !NO_JSONLINQ
private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id)
{
id = null;
newValue = null;
if (reader.TokenType == JsonToken.StartObject)
{
JObject current = (JObject)reader.CurrentToken;
JToken refToken = current[JsonTypeReflector.RefPropertyName];
if (refToken != null)
{
if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null)
{
throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null);
}
JToken property = refToken.Parent;
JToken additionalContent = null;
if (property.Next != null)
{
additionalContent = property.Next;
}
else if (property.Previous != null)
{
additionalContent = property.Previous;
}
string reference = (string)refToken;
if (reference != null)
{
if (additionalContent != null)
{
throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null);
}
newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null);
}
reader.Skip();
return true;
}
}
JToken typeToken = current[JsonTypeReflector.TypePropertyName];
if (typeToken != null)
{
string qualifiedTypeName = (string)typeToken;
JsonReader typeTokenReader = typeToken.CreateReader();
typeTokenReader.ReadAndAssert();
ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName);
JToken valueToken = current[JsonTypeReflector.ValuePropertyName];
if (valueToken != null)
{
while (true)
{
reader.ReadAndAssert();
if (reader.TokenType == JsonToken.PropertyName)
{
if ((string)reader.Value == JsonTypeReflector.ValuePropertyName)
{
return false;
}
}
reader.ReadAndAssert();
reader.Skip();
}
}
}
JToken idToken = current[JsonTypeReflector.IdPropertyName];
if (idToken != null)
{
id = (string)idToken;
}
JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName];
if (valuesToken != null)
{
JsonReader listReader = valuesToken.CreateReader();
listReader.ReadAndAssert();
newValue = CreateList(listReader, objectType, contract, member, existingValue, id);
reader.Skip();
return true;
}
}
reader.ReadAndAssert();
return false;
}
#endif
private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id)
{
id = null;
newValue = null;
if (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value.ToString();
if (propertyName.Length > 0 && propertyName[0] == '$')
{
// read metadata properties
// $type, $id, $ref, etc
bool metadataProperty;
do
{
propertyName = reader.Value.ToString();
if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal))
{
reader.ReadAndAssert();
if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null)
{
throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));
}
string reference = (reader.Value != null) ? reader.Value.ToString() : null;
reader.ReadAndAssert();
if (reference != null)
{
if (reader.TokenType == JsonToken.PropertyName)
{
throw JsonSerializationException.Create(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName));
}
newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null);
}
return true;
}
else
{
metadataProperty = true;
}
}
else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal))
{
reader.ReadAndAssert();
string qualifiedTypeName = reader.Value.ToString();
ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName);
reader.ReadAndAssert();
metadataProperty = true;
}
else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal))
{
reader.ReadAndAssert();
id = (reader.Value != null) ? reader.Value.ToString() : null;
reader.ReadAndAssert();
metadataProperty = true;
}
else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal))
{
reader.ReadAndAssert();
object list = CreateList(reader, objectType, contract, member, existingValue, id);
reader.ReadAndAssert();
newValue = list;
return true;
}
else
{
metadataProperty = false;
}
} while (metadataProperty && reader.TokenType == JsonToken.PropertyName);
}
}
return false;
}
private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, string qualifiedTypeName)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? ((containerMember != null) ? containerMember.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (resolvedTypeNameHandling != TypeNameHandling.None)
{
string typeName;
string assemblyName;
ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName);
Type specifiedType;
try
{
specifiedType = Serializer._binder.BindToType(assemblyName, typeName);
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex);
}
if (specifiedType == null)
{
throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName));
}
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved type '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName, specifiedType)), null);
}
if (objectType != null
#if !(NET35 || NET20 || PORTABLE40)
&& objectType != typeof(IDynamicMetaObjectProvider)
#endif
&& !objectType.IsAssignableFrom(specifiedType))
{
throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName));
}
objectType = specifiedType;
contract = GetContractSafe(specifiedType);
}
}
private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)
{
if (contract == null)
{
throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
JsonArrayContract arrayContract = contract as JsonArrayContract;
if (arrayContract == null)
{
string message = @"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '{0}' because the type requires a {1} to deserialize correctly." + Environment.NewLine +
@"To fix this error either change the JSON to a {1} or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, objectType, GetExpectedDescription(contract));
throw JsonSerializationException.Create(reader, message);
}
return arrayContract;
}
private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string id)
{
object value;
if (HasNoDefinedType(contract))
{
#if NO_JSONLINQ
return null;
#else
return CreateJToken(reader, contract);
#endif
}
JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract);
if (existingValue == null)
{
bool createdFromNonDefaultCreator;
IList list = CreateNewList(reader, arrayContract, out createdFromNonDefaultCreator);
if (createdFromNonDefaultCreator)
{
if (id != null)
{
throw JsonSerializationException.Create(reader, "Cannot preserve reference to array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
if (contract.OnSerializingCallbacks.Count > 0)
{
throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on an array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
if (contract.OnErrorCallbacks.Count > 0)
{
throw JsonSerializationException.Create(reader, "Cannot call OnError on an array or readonly list, or list created from a non-default constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
if (!arrayContract.HasParameterizedCreatorInternal && !arrayContract.IsArray)
{
throw JsonSerializationException.Create(reader, "Cannot deserialize readonly or fixed size list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
}
}
if (!arrayContract.IsMultidimensionalArray)
{
PopulateList(list, reader, arrayContract, member, id);
}
else
{
PopulateMultidimensionalArray(list, reader, arrayContract, member, id);
}
if (createdFromNonDefaultCreator)
{
if (arrayContract.IsMultidimensionalArray)
{
list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType, contract.CreatedType.GetArrayRank());
}
else if (arrayContract.IsArray)
{
Array a = Array.CreateInstance(arrayContract.CollectionItemType, list.Count);
list.CopyTo(a, 0);
list = a;
}
else
{
ObjectConstructor<object> creator = arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator;
return creator(list);
}
}
else if (list is IWrappedCollection)
{
return ((IWrappedCollection)list).UnderlyingCollection;
}
value = list;
}
else
{
if (!arrayContract.CanDeserialize)
{
throw JsonSerializationException.Create(reader, "Cannot populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.CreatedType));
}
value = PopulateList((arrayContract.ShouldCreateWrapper) ? arrayContract.CreateWrapper(existingValue) : (IList)existingValue, reader, arrayContract, member, id);
}
return value;
}
private bool HasNoDefinedType(JsonContract contract)
{
return (contract == null || contract.UnderlyingType == typeof(object) || contract.ContractType == JsonContractType.Linq
#if !(NET35 || NET20 || PORTABLE40)
|| contract.UnderlyingType == typeof(IDynamicMetaObjectProvider)
#endif
);
}
private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType)
{
if (targetType == null)
{
return value;
}
Type valueType = ReflectionUtils.GetObjectType(value);
// type of value and type of target don't match
// attempt to convert value's type to target's type
if (valueType != targetType)
{
if (value == null && contract.IsNullable)
{
return null;
}
try
{
if (contract.IsConvertable)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (contract.IsEnum)
{
if (value is string)
{
return Enum.Parse(contract.NonNullableUnderlyingType, value.ToString(), true);
}
if (ConvertUtils.IsInteger(primitiveContract.TypeCode))
{
return Enum.ToObject(contract.NonNullableUnderlyingType, value);
}
}
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
if (value is BigInteger)
{
return ConvertUtils.FromBigInteger((BigInteger)value, contract.NonNullableUnderlyingType);
}
#endif
// this won't work when converting to a custom IConvertible
return Convert.ChangeType(value, contract.NonNullableUnderlyingType, culture);
}
return ConvertUtils.ConvertOrCast(value, culture, contract.NonNullableUnderlyingType);