-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
DefaultContractResolver.cs
1699 lines (1453 loc) · 72.2 KB
/
DefaultContractResolver.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;
#if HAVE_CONCURRENT_DICTIONARY
using System.Collections.Concurrent;
#endif
using Newtonsoft.Json.Schema;
using System.Collections.Generic;
using System.ComponentModel;
#if HAVE_DYNAMIC
using System.Dynamic;
#endif
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
#if HAVE_CAS
using System.Security.Permissions;
#endif
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Runtime.CompilerServices;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Used by <see cref="JsonSerializer"/> to resolve a <see cref="JsonContract"/> for a given <see cref="System.Type"/>.
/// </summary>
public class DefaultContractResolver : IContractResolver
{
private static readonly IContractResolver _instance = new DefaultContractResolver();
// Json.NET Schema requires a property
internal static IContractResolver Instance => _instance;
private static readonly string[] BlacklistedTypeNames =
{
"System.IO.DriveInfo",
"System.IO.FileInfo",
"System.IO.DirectoryInfo"
};
private static readonly JsonConverter[] BuiltInConverters =
{
#if HAVE_ENTITY_FRAMEWORK
new EntityKeyMemberConverter(),
#endif
#if HAVE_DYNAMIC
new ExpandoObjectConverter(),
#endif
#if (HAVE_XML_DOCUMENT || HAVE_XLINQ)
new XmlNodeConverter(),
#endif
#if HAVE_ADO_NET
new BinaryConverter(),
new DataSetConverter(),
new DataTableConverter(),
#endif
#if HAVE_FSHARP_TYPES
new DiscriminatedUnionConverter(),
#endif
new KeyValuePairConverter(),
#pragma warning disable 618
new BsonObjectIdConverter(),
#pragma warning restore 618
new RegexConverter()
};
private readonly DefaultJsonNameTable _nameTable = new DefaultJsonNameTable();
private readonly ThreadSafeStore<Type, JsonContract> _contractCache;
/// <summary>
/// Gets a value indicating whether members are being get and set using dynamic code generation.
/// This value is determined by the runtime permissions available.
/// </summary>
/// <value>
/// <c>true</c> if using dynamic code generation; otherwise, <c>false</c>.
/// </value>
public bool DynamicCodeGeneration => JsonTypeReflector.DynamicCodeGeneration;
#if !PORTABLE
/// <summary>
/// Gets or sets the default members search flags.
/// </summary>
/// <value>The default members search flags.</value>
[Obsolete("DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")]
public BindingFlags DefaultMembersSearchFlags { get; set; }
#else
private BindingFlags DefaultMembersSearchFlags;
#endif
/// <summary>
/// Gets or sets a value indicating whether compiler generated members should be serialized.
/// </summary>
/// <value>
/// <c>true</c> if serialized compiler generated members; otherwise, <c>false</c>.
/// </value>
public bool SerializeCompilerGeneratedMembers { get; set; }
#if HAVE_BINARY_SERIALIZATION
/// <summary>
/// Gets or sets a value indicating whether to ignore the <see cref="ISerializable"/> interface when serializing and deserializing types.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="ISerializable"/> interface will be ignored when serializing and deserializing types; otherwise, <c>false</c>.
/// </value>
public bool IgnoreSerializableInterface { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore the <see cref="SerializableAttribute"/> attribute when serializing and deserializing types.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="SerializableAttribute"/> attribute will be ignored when serializing and deserializing types; otherwise, <c>false</c>.
/// </value>
public bool IgnoreSerializableAttribute { get; set; }
#endif
/// <summary>
/// Gets or sets a value indicating whether to ignore IsSpecified members when serializing and deserializing types.
/// </summary>
/// <value>
/// <c>true</c> if the IsSpecified members will be ignored when serializing and deserializing types; otherwise, <c>false</c>.
/// </value>
public bool IgnoreIsSpecifiedMembers { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore ShouldSerialize members when serializing and deserializing types.
/// </summary>
/// <value>
/// <c>true</c> if the ShouldSerialize members will be ignored when serializing and deserializing types; otherwise, <c>false</c>.
/// </value>
public bool IgnoreShouldSerializeMembers { get; set; }
/// <summary>
/// Gets or sets the naming strategy used to resolve how property names and dictionary keys are serialized.
/// </summary>
/// <value>The naming strategy used to resolve how property names and dictionary keys are serialized.</value>
public NamingStrategy NamingStrategy { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DefaultContractResolver"/> class.
/// </summary>
public DefaultContractResolver()
{
#if HAVE_BINARY_SERIALIZATION
IgnoreSerializableAttribute = true;
#endif
#pragma warning disable 618
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.Public;
#pragma warning restore 618
_contractCache = new ThreadSafeStore<Type, JsonContract>(CreateContract);
}
/// <summary>
/// Resolves the contract for a given type.
/// </summary>
/// <param name="type">The type to resolve a contract for.</param>
/// <returns>The contract for a given type.</returns>
public virtual JsonContract ResolveContract(Type type)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
return _contractCache.Get(type);
}
/// <summary>
/// Gets the serializable members for the type.
/// </summary>
/// <param name="objectType">The type to get serializable members for.</param>
/// <returns>The serializable members for the type.</returns>
protected virtual List<MemberInfo> GetSerializableMembers(Type objectType)
{
bool ignoreSerializableAttribute;
#if HAVE_BINARY_SERIALIZATION
ignoreSerializableAttribute = IgnoreSerializableAttribute;
#else
ignoreSerializableAttribute = true;
#endif
MemberSerialization memberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute);
IEnumerable<MemberInfo> allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
.Where(m => !ReflectionUtils.IsIndexedProperty(m));
List<MemberInfo> serializableMembers = new List<MemberInfo>();
if (memberSerialization != MemberSerialization.Fields)
{
#if HAVE_DATA_CONTRACTS
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType);
#endif
#pragma warning disable 618
List<MemberInfo> defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags)
.Where(m => !ReflectionUtils.IsIndexedProperty(m)).ToList();
#pragma warning restore 618
foreach (MemberInfo member in allMembers)
{
// exclude members that are compiler generated if set
if (SerializeCompilerGeneratedMembers || !member.IsDefined(typeof(CompilerGeneratedAttribute), true))
{
if (defaultMembers.Contains(member))
{
// add all members that are found by default member search
serializableMembers.Add(member);
}
else
{
// add members that are explicitly marked with JsonProperty/DataMember attribute
// or are a field if serializing just fields
if (JsonTypeReflector.GetAttribute<JsonPropertyAttribute>(member) != null)
{
serializableMembers.Add(member);
}
else if (JsonTypeReflector.GetAttribute<JsonRequiredAttribute>(member) != null)
{
serializableMembers.Add(member);
}
#if HAVE_DATA_CONTRACTS
else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute<DataMemberAttribute>(member) != null)
{
serializableMembers.Add(member);
}
#endif
else if (memberSerialization == MemberSerialization.Fields && member.MemberType() == MemberTypes.Field)
{
serializableMembers.Add(member);
}
}
}
}
#if HAVE_DATA_CONTRACTS
Type match;
// don't include EntityKey on entities objects... this is a bit hacky
if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", false, out match))
{
serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList();
}
#endif
}
else
{
// serialize all fields
foreach (MemberInfo member in allMembers)
{
if (member is FieldInfo field && !field.IsStatic)
{
serializableMembers.Add(member);
}
}
}
return serializableMembers;
}
#if HAVE_DATA_CONTRACTS
private bool ShouldSerializeEntityMember(MemberInfo memberInfo)
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
{
if (propertyInfo.PropertyType.IsGenericType() && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1")
{
return false;
}
}
return true;
}
#endif
/// <summary>
/// Creates a <see cref="JsonObjectContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonObjectContract"/> for the given type.</returns>
protected virtual JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = new JsonObjectContract(objectType);
InitializeContract(contract);
bool ignoreSerializableAttribute;
#if HAVE_BINARY_SERIALIZATION
ignoreSerializableAttribute = IgnoreSerializableAttribute;
#else
ignoreSerializableAttribute = true;
#endif
contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType, ignoreSerializableAttribute);
contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization));
Func<string, string> extensionDataNameResolver = null;
JsonObjectAttribute attribute = JsonTypeReflector.GetCachedAttribute<JsonObjectAttribute>(contract.NonNullableUnderlyingType);
if (attribute != null)
{
contract.ItemRequired = attribute._itemRequired;
contract.ItemNullValueHandling = attribute._itemNullValueHandling;
if (attribute.NamingStrategyType != null)
{
NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(attribute);
extensionDataNameResolver = s => namingStrategy.GetDictionaryKey(s);
}
}
if (extensionDataNameResolver == null)
{
extensionDataNameResolver = ResolveExtensionDataName;
}
contract.ExtensionDataNameResolver = extensionDataNameResolver;
if (contract.IsInstantiable)
{
ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType);
// check if a JsonConstructorAttribute has been defined and use that
if (overrideConstructor != null)
{
contract.OverrideCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(overrideConstructor);
contract.CreatorParameters.AddRange(CreateConstructorParameters(overrideConstructor, contract.Properties));
}
else if (contract.MemberSerialization == MemberSerialization.Fields)
{
#if HAVE_BINARY_FORMATTER
// mimic DataContractSerializer behaviour when populating fields by overriding default creator to create an uninitialized object
// note that this is only possible when the application is fully trusted so fall back to using the default constructor (if available) in partial trust
if (JsonTypeReflector.FullyTrusted)
{
contract.DefaultCreator = contract.GetUninitializedObject;
}
#endif
}
else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic)
{
ConstructorInfo constructor = GetParameterizedConstructor(contract.NonNullableUnderlyingType);
if (constructor != null)
{
contract.ParameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor);
contract.CreatorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties));
}
}
else if (contract.NonNullableUnderlyingType.IsValueType())
{
// value types always have default constructor
// check whether there is a constructor that matches with non-writable properties on value type
ConstructorInfo constructor = GetImmutableConstructor(contract.NonNullableUnderlyingType, contract.Properties);
if (constructor != null)
{
contract.OverrideCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor);
contract.CreatorParameters.AddRange(CreateConstructorParameters(constructor, contract.Properties));
}
}
}
MemberInfo extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType);
if (extensionDataMember != null)
{
SetExtensionDataDelegates(contract, extensionDataMember);
}
// serializing DirectoryInfo without ISerializable will stackoverflow
// https://github.com/JamesNK/Newtonsoft.Json/issues/1541
if (Array.IndexOf(BlacklistedTypeNames, objectType.FullName) != -1)
{
contract.OnSerializingCallbacks.Add(ThrowUnableToSerializeError);
}
return contract;
}
private static void ThrowUnableToSerializeError(object o, StreamingContext context)
{
throw new JsonSerializationException("Unable to serialize instance of '{0}'.".FormatWith(CultureInfo.InvariantCulture, o.GetType()));
}
private MemberInfo GetExtensionDataMemberForType(Type type)
{
IEnumerable<MemberInfo> members = GetClassHierarchyForType(type).SelectMany(baseType =>
{
IList<MemberInfo> m = new List<MemberInfo>();
m.AddRange(baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
m.AddRange(baseType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
return m;
});
MemberInfo extensionDataMember = members.LastOrDefault(m =>
{
MemberTypes memberType = m.MemberType();
if (memberType != MemberTypes.Property && memberType != MemberTypes.Field)
{
return false;
}
// last instance of attribute wins on type if there are multiple
if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false))
{
return false;
}
if (!ReflectionUtils.CanReadMemberValue(m, true))
{
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
}
Type t = ReflectionUtils.GetMemberUnderlyingType(m);
if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType))
{
Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1];
if (keyType.IsAssignableFrom(typeof(string)) && valueType.IsAssignableFrom(typeof(JToken)))
{
return true;
}
}
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
});
return extensionDataMember;
}
private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member)
{
JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute<JsonExtensionDataAttribute>(member);
if (extensionDataAttribute == null)
{
return;
}
Type t = ReflectionUtils.GetMemberUnderlyingType(member);
ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType);
Type keyType = dictionaryType.GetGenericArguments()[0];
Type valueType = dictionaryType.GetGenericArguments()[1];
Type createdType;
// change type to a class if it is the base interface so it can be instantiated if needed
if (ReflectionUtils.IsGenericDefinition(t, typeof(IDictionary<,>)))
{
createdType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
}
else
{
createdType = t;
}
Func<object, object> getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(member);
if (extensionDataAttribute.ReadData)
{
Action<object, object> setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false))
? JsonTypeReflector.ReflectionDelegateFactory.CreateSet<object>(member)
: null;
Func<object> createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
MethodInfo addMethod = t.GetMethod("Add", new[] { keyType, valueType });
if (addMethod == null)
{
// Add is explicitly implemented and non-public
// get from dictionary interface
addMethod = dictionaryType.GetMethod("Add", new[] {keyType, valueType});
}
MethodCall<object, object> setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(addMethod);
ExtensionDataSetter extensionDataSetter = (o, key, value) =>
{
object dictionary = getExtensionDataDictionary(o);
if (dictionary == null)
{
if (setExtensionDataDictionary == null)
{
throw new JsonSerializationException("Cannot set value onto extension data member '{0}'. The extension data collection is null and it cannot be set.".FormatWith(CultureInfo.InvariantCulture, member.Name));
}
dictionary = createExtensionDataDictionary();
setExtensionDataDictionary(o, dictionary);
}
setExtensionDataDictionaryValue(dictionary, key, value);
};
contract.ExtensionDataSetter = extensionDataSetter;
}
if (extensionDataAttribute.WriteData)
{
Type enumerableWrapper = typeof(EnumerableDictionaryWrapper<,>).MakeGenericType(keyType, valueType);
ConstructorInfo constructors = enumerableWrapper.GetConstructors().First();
ObjectConstructor<object> createEnumerableWrapper = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructors);
ExtensionDataGetter extensionDataGetter = o =>
{
object dictionary = getExtensionDataDictionary(o);
if (dictionary == null)
{
return null;
}
return (IEnumerable<KeyValuePair<object, object>>)createEnumerableWrapper(dictionary);
};
contract.ExtensionDataGetter = extensionDataGetter;
}
contract.ExtensionDataValueType = valueType;
}
// leave as class instead of struct
// will be always return as an interface and boxed
internal class EnumerableDictionaryWrapper<TEnumeratorKey, TEnumeratorValue> : IEnumerable<KeyValuePair<object, object>>
{
private readonly IEnumerable<KeyValuePair<TEnumeratorKey, TEnumeratorValue>> _e;
public EnumerableDictionaryWrapper(IEnumerable<KeyValuePair<TEnumeratorKey, TEnumeratorValue>> e)
{
ValidationUtils.ArgumentNotNull(e, nameof(e));
_e = e;
}
public IEnumerator<KeyValuePair<object, object>> GetEnumerator()
{
foreach (KeyValuePair<TEnumeratorKey, TEnumeratorValue> item in _e)
{
yield return new KeyValuePair<object, object>(item.Key, item.Value);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
private ConstructorInfo GetAttributeConstructor(Type objectType)
{
IEnumerator<ConstructorInfo> en = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).GetEnumerator();
if (en.MoveNext())
{
ConstructorInfo conInfo = en.Current;
if (en.MoveNext())
{
throw new JsonException("Multiple constructors with the JsonConstructorAttribute.");
}
return conInfo;
}
// little hack to get Version objects to deserialize correctly
if (objectType == typeof(Version))
{
return objectType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int) });
}
return null;
}
private ConstructorInfo GetImmutableConstructor(Type objectType, JsonPropertyCollection memberProperties)
{
IEnumerable<ConstructorInfo> constructors = objectType.GetConstructors();
IEnumerator<ConstructorInfo> en = constructors.GetEnumerator();
if (en.MoveNext())
{
ConstructorInfo constructor = en.Current;
if (!en.MoveNext())
{
ParameterInfo[] parameters = constructor.GetParameters();
if (parameters.Length > 0)
{
foreach (ParameterInfo parameterInfo in parameters)
{
JsonProperty memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType);
if (memberProperty == null || memberProperty.Writable)
{
return null;
}
}
return constructor;
}
}
}
return null;
}
private ConstructorInfo GetParameterizedConstructor(Type objectType)
{
#if PORTABLE
IEnumerable<ConstructorInfo> constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
IEnumerator<ConstructorInfo> en = constructors.GetEnumerator();
if (en.MoveNext())
{
ConstructorInfo conInfo = en.Current;
if (!en.MoveNext())
{
return conInfo;
}
}
#else
ConstructorInfo[] constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
if (constructors.Length == 1)
{
return constructors[0];
}
#endif
return null;
}
/// <summary>
/// Creates the constructor parameters.
/// </summary>
/// <param name="constructor">The constructor to create properties for.</param>
/// <param name="memberProperties">The type's member properties.</param>
/// <returns>Properties for the given <see cref="ConstructorInfo"/>.</returns>
protected virtual IList<JsonProperty> CreateConstructorParameters(ConstructorInfo constructor, JsonPropertyCollection memberProperties)
{
ParameterInfo[] constructorParameters = constructor.GetParameters();
JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType);
foreach (ParameterInfo parameterInfo in constructorParameters)
{
JsonProperty matchingMemberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType);
// ensure that property will have a name from matching property or from parameterinfo
// parameterinfo could have no name if generated by a proxy (I'm looking at you Castle)
if (matchingMemberProperty != null || parameterInfo.Name != null)
{
JsonProperty property = CreatePropertyFromConstructorParameter(matchingMemberProperty, parameterInfo);
if (property != null)
{
parameterCollection.AddProperty(property);
}
}
}
return parameterCollection;
}
private JsonProperty MatchProperty(JsonPropertyCollection properties, string name, Type type)
{
// it is possible to generate a member with a null name using Reflection.Emit
// protect against an ArgumentNullException from GetClosestMatchProperty by testing for null here
if (name == null)
{
return null;
}
JsonProperty property = properties.GetClosestMatchProperty(name);
// must match type as well as name
if (property == null || property.PropertyType != type)
{
return null;
}
return property;
}
/// <summary>
/// Creates a <see cref="JsonProperty"/> for the given <see cref="ParameterInfo"/>.
/// </summary>
/// <param name="matchingMemberProperty">The matching member property.</param>
/// <param name="parameterInfo">The constructor parameter.</param>
/// <returns>A created <see cref="JsonProperty"/> for the given <see cref="ParameterInfo"/>.</returns>
protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo)
{
JsonProperty property = new JsonProperty();
property.PropertyType = parameterInfo.ParameterType;
property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo);
SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out _);
property.Readable = false;
property.Writable = true;
// "inherit" values from matching member property if unset on parameter
if (matchingMemberProperty != null)
{
property.PropertyName = (property.PropertyName != parameterInfo.Name) ? property.PropertyName : matchingMemberProperty.PropertyName;
property.Converter = property.Converter ?? matchingMemberProperty.Converter;
if (!property._hasExplicitDefaultValue && matchingMemberProperty._hasExplicitDefaultValue)
{
property.DefaultValue = matchingMemberProperty.DefaultValue;
}
property._required = property._required ?? matchingMemberProperty._required;
property.IsReference = property.IsReference ?? matchingMemberProperty.IsReference;
property.NullValueHandling = property.NullValueHandling ?? matchingMemberProperty.NullValueHandling;
property.DefaultValueHandling = property.DefaultValueHandling ?? matchingMemberProperty.DefaultValueHandling;
property.ReferenceLoopHandling = property.ReferenceLoopHandling ?? matchingMemberProperty.ReferenceLoopHandling;
property.ObjectCreationHandling = property.ObjectCreationHandling ?? matchingMemberProperty.ObjectCreationHandling;
property.TypeNameHandling = property.TypeNameHandling ?? matchingMemberProperty.TypeNameHandling;
}
return property;
}
/// <summary>
/// Resolves the default <see cref="JsonConverter" /> for the contract.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>The contract's default <see cref="JsonConverter" />.</returns>
protected virtual JsonConverter ResolveContractConverter(Type objectType)
{
return JsonTypeReflector.GetJsonConverter(objectType);
}
private Func<object> GetDefaultCreator(Type createdType)
{
return JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(createdType);
}
#if NET35
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Runtime.Serialization.DataContractAttribute.#get_IsReference()")]
#endif
private void InitializeContract(JsonContract contract)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(contract.NonNullableUnderlyingType);
if (containerAttribute != null)
{
contract.IsReference = containerAttribute._isReference;
}
#if HAVE_DATA_CONTRACTS
else
{
DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType);
// doesn't have a null value
if (dataContractAttribute != null && dataContractAttribute.IsReference)
{
contract.IsReference = true;
}
}
#endif
contract.Converter = ResolveContractConverter(contract.NonNullableUnderlyingType);
// then see whether object is compatible with any of the built in converters
contract.InternalConverter = JsonSerializer.GetMatchingConverter(BuiltInConverters, contract.NonNullableUnderlyingType);
if (contract.IsInstantiable
&& (ReflectionUtils.HasDefaultConstructor(contract.CreatedType, true) || contract.CreatedType.IsValueType()))
{
contract.DefaultCreator = GetDefaultCreator(contract.CreatedType);
contract.DefaultCreatorNonPublic = (!contract.CreatedType.IsValueType() &&
ReflectionUtils.GetDefaultConstructor(contract.CreatedType) == null);
}
ResolveCallbackMethods(contract, contract.NonNullableUnderlyingType);
}
private void ResolveCallbackMethods(JsonContract contract, Type t)
{
GetCallbackMethodsForType(
t,
out List<SerializationCallback> onSerializing,
out List<SerializationCallback> onSerialized,
out List<SerializationCallback> onDeserializing,
out List<SerializationCallback> onDeserialized,
out List<SerializationErrorCallback> onError);
if (onSerializing != null)
{
contract.OnSerializingCallbacks.AddRange(onSerializing);
}
if (onSerialized != null)
{
contract.OnSerializedCallbacks.AddRange(onSerialized);
}
if (onDeserializing != null)
{
contract.OnDeserializingCallbacks.AddRange(onDeserializing);
}
if (onDeserialized != null)
{
contract.OnDeserializedCallbacks.AddRange(onDeserialized);
}
if (onError != null)
{
contract.OnErrorCallbacks.AddRange(onError);
}
}
private void GetCallbackMethodsForType(Type type, out List<SerializationCallback> onSerializing, out List<SerializationCallback> onSerialized, out List<SerializationCallback> onDeserializing, out List<SerializationCallback> onDeserialized, out List<SerializationErrorCallback> onError)
{
onSerializing = null;
onSerialized = null;
onDeserializing = null;
onDeserialized = null;
onError = null;
foreach (Type baseType in GetClassHierarchyForType(type))
{
// while we allow more than one OnSerialized total, only one can be defined per class
MethodInfo currentOnSerializing = null;
MethodInfo currentOnSerialized = null;
MethodInfo currentOnDeserializing = null;
MethodInfo currentOnDeserialized = null;
MethodInfo currentOnError = null;
bool skipSerializing = ShouldSkipSerializing(baseType);
bool skipDeserialized = ShouldSkipDeserialized(baseType);
foreach (MethodInfo method in baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
// compact framework errors when getting parameters for a generic method
// lame, but generic methods should not be callbacks anyway
if (method.ContainsGenericParameters)
{
continue;
}
Type prevAttributeType = null;
ParameterInfo[] parameters = method.GetParameters();
if (!skipSerializing && IsValidCallback(method, parameters, typeof(OnSerializingAttribute), currentOnSerializing, ref prevAttributeType))
{
onSerializing = onSerializing ?? new List<SerializationCallback>();
onSerializing.Add(JsonContract.CreateSerializationCallback(method));
currentOnSerializing = method;
}
if (IsValidCallback(method, parameters, typeof(OnSerializedAttribute), currentOnSerialized, ref prevAttributeType))
{
onSerialized = onSerialized ?? new List<SerializationCallback>();
onSerialized.Add(JsonContract.CreateSerializationCallback(method));
currentOnSerialized = method;
}
if (IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), currentOnDeserializing, ref prevAttributeType))
{
onDeserializing = onDeserializing ?? new List<SerializationCallback>();
onDeserializing.Add(JsonContract.CreateSerializationCallback(method));
currentOnDeserializing = method;
}
if (!skipDeserialized && IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), currentOnDeserialized, ref prevAttributeType))
{
onDeserialized = onDeserialized ?? new List<SerializationCallback>();
onDeserialized.Add(JsonContract.CreateSerializationCallback(method));
currentOnDeserialized = method;
}
if (IsValidCallback(method, parameters, typeof(OnErrorAttribute), currentOnError, ref prevAttributeType))
{
onError = onError ?? new List<SerializationErrorCallback>();
onError.Add(JsonContract.CreateSerializationErrorCallback(method));
currentOnError = method;
}
}
}
}
private static bool IsConcurrentOrObservableCollection(Type t)
{
if (t.IsGenericType())
{
Type definition = t.GetGenericTypeDefinition();
switch (definition.FullName)
{
case "System.Collections.Concurrent.ConcurrentQueue`1":
case "System.Collections.Concurrent.ConcurrentStack`1":
case "System.Collections.Concurrent.ConcurrentBag`1":
case JsonTypeReflector.ConcurrentDictionaryTypeName:
case "System.Collections.ObjectModel.ObservableCollection`1":
return true;
}
}
return false;
}
private static bool ShouldSkipDeserialized(Type t)
{
// ConcurrentDictionary throws an error in its OnDeserialized so ignore - http://json.codeplex.com/discussions/257093
if (IsConcurrentOrObservableCollection(t))
{
return true;
}
#if HAVE_FSHARP_TYPES
if (t.Name == FSharpUtils.FSharpSetTypeName || t.Name == FSharpUtils.FSharpMapTypeName)
{
return true;
}
#endif
return false;
}
private static bool ShouldSkipSerializing(Type t)
{
if (IsConcurrentOrObservableCollection(t))
{
return true;
}
#if HAVE_FSHARP_TYPES
if (t.Name == FSharpUtils.FSharpSetTypeName || t.Name == FSharpUtils.FSharpMapTypeName)
{
return true;
}
#endif
return false;
}
private List<Type> GetClassHierarchyForType(Type type)
{
List<Type> ret = new List<Type>();
Type current = type;
while (current != null && current != typeof(object))
{
ret.Add(current);
current = current.BaseType();
}
// Return the class list in order of simple => complex
ret.Reverse();
return ret;
}
/// <summary>
/// Creates a <see cref="JsonDictionaryContract"/> for the given type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>A <see cref="JsonDictionaryContract"/> for the given type.</returns>
protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = new JsonDictionaryContract(objectType);
InitializeContract(contract);
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetAttribute<JsonContainerAttribute>(objectType);
if (containerAttribute?.NamingStrategyType != null)
{
NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute);
contract.DictionaryKeyResolver = s => namingStrategy.GetDictionaryKey(s);
}
else
{
contract.DictionaryKeyResolver = ResolveDictionaryKey;
}
ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType);
if (overrideConstructor != null)
{
ParameterInfo[] parameters = overrideConstructor.GetParameters();
Type expectedParameterType = (contract.DictionaryKeyType != null && contract.DictionaryValueType != null)
? typeof(IEnumerable<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(contract.DictionaryKeyType, contract.DictionaryValueType))
: typeof(IDictionary);