-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathJsonTypeInfo.cs
More file actions
1412 lines (1217 loc) · 60.4 KB
/
Copy pathJsonTypeInfo.cs
File metadata and controls
1412 lines (1217 loc) · 60.4 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Text.Json.Reflection;
using System.Text.Json.Serialization.Converters;
using System.Threading;
using System.Threading.Tasks;
namespace System.Text.Json.Serialization.Metadata
{
/// <summary>
/// Provides JSON serialization-related metadata about a type.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public abstract partial class JsonTypeInfo
{
internal const string MetadataFactoryRequiresUnreferencedCode = "JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.";
internal const string JsonObjectTypeName = "System.Text.Json.Nodes.JsonObject";
internal delegate T ParameterizedConstructorDelegate<T, TArg0, TArg1, TArg2, TArg3>(TArg0? arg0, TArg1? arg1, TArg2? arg2, TArg3? arg3);
/// <summary>
/// Indices of required properties.
/// </summary>
internal int NumberOfRequiredProperties { get; private set; }
private Action<object>? _onSerializing;
private Action<object>? _onSerialized;
private Action<object>? _onDeserializing;
private Action<object>? _onDeserialized;
internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options)
{
Type = type;
Options = options;
Converter = converter;
Kind = GetTypeInfoKind(type, converter);
PropertyInfoForTypeInfo = CreatePropertyInfoForTypeInfo();
ElementType = converter.ElementType;
KeyType = converter.KeyType;
}
/// <summary>
/// Gets or sets a parameterless factory to be used on deserialization.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// A parameterless factory is not supported for the current metadata <see cref="Kind"/>.
/// </exception>
/// <remarks>
/// If set to <see langword="null" />, any attempt to deserialize instances of the given type will result in an exception.
///
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// types with a single default constructor or default constructors annotated with <see cref="JsonConstructorAttribute"/>
/// will be mapped to this delegate.
/// </remarks>
public Func<object>? CreateObject
{
get => _createObject;
set
{
SetCreateObject(value);
}
}
private protected abstract void SetCreateObject(Delegate? createObject);
private protected Func<object>? _createObject;
internal Func<object>? CreateObjectForExtensionDataProperty { get; set; }
/// <summary>
/// Gets or sets a callback to be invoked before serialization occurs.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from any <see cref="IJsonOnSerializing"/> implementation on the type.
/// </remarks>
public Action<object>? OnSerializing
{
get => _onSerializing;
set
{
VerifyMutable();
if (Kind != JsonTypeInfoKind.Object)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
_onSerializing = value;
}
}
/// <summary>
/// Gets or sets a callback to be invoked after serialization occurs.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from any <see cref="IJsonOnSerialized"/> implementation on the type.
/// </remarks>
public Action<object>? OnSerialized
{
get => _onSerialized;
set
{
VerifyMutable();
if (Kind != JsonTypeInfoKind.Object)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
_onSerialized = value;
}
}
/// <summary>
/// Gets or sets a callback to be invoked before deserialization occurs.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from any <see cref="IJsonOnDeserializing"/> implementation on the type.
/// </remarks>
public Action<object>? OnDeserializing
{
get => _onDeserializing;
set
{
VerifyMutable();
if (Kind != JsonTypeInfoKind.Object)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
_onDeserializing = value;
}
}
/// <summary>
/// Gets or sets a callback to be invoked after deserialization occurs.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from any <see cref="IJsonOnDeserialized"/> implementation on the type.
/// </remarks>
public Action<object>? OnDeserialized
{
get => _onDeserialized;
set
{
VerifyMutable();
if (Kind != JsonTypeInfoKind.Object)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
_onDeserialized = value;
}
}
/// <summary>
/// Gets the list of <see cref="JsonPropertyInfo"/> metadata corresponding to the current type.
/// </summary>
/// <remarks>
/// Property is only applicable to metadata of kind <see cref="JsonTypeInfoKind.Object"/>.
/// For other kinds an empty, read-only list will be returned.
///
/// The order of <see cref="JsonPropertyInfo"/> entries in the list determines the serialization order,
/// unless either of the entries specifies a non-zero <see cref="JsonPropertyInfo.Order"/> value,
/// in which case the properties will be stable sorted by <see cref="JsonPropertyInfo.Order"/>.
///
/// It is required that added <see cref="JsonPropertyInfo"/> entries are unique up to <see cref="JsonPropertyInfo.Name"/>,
/// however this will only be validated on serialization, once the metadata instance gets locked for further modification.
/// </remarks>
public IList<JsonPropertyInfo> Properties => PropertyList;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal JsonPropertyInfoList PropertyList
{
get
{
return _properties ?? CreatePropertyList();
JsonPropertyInfoList CreatePropertyList()
{
var list = new JsonPropertyInfoList(this);
if (_sourceGenDelayedPropertyInitializer is { } propInit)
{
// .NET 6 source gen backward compatibility -- ensure that the
// property initializer delegate is invoked lazily.
JsonMetadataServices.PopulateProperties(this, list, propInit);
}
JsonPropertyInfoList? result = Interlocked.CompareExchange(ref _properties, list, null);
_sourceGenDelayedPropertyInitializer = null;
return result ?? list;
}
}
}
/// <summary>
/// Stores the .NET 6-style property initialization delegate for delayed evaluation.
/// </summary>
internal Func<JsonSerializerContext, JsonPropertyInfo[]>? SourceGenDelayedPropertyInitializer
{
get => _sourceGenDelayedPropertyInitializer;
set
{
Debug.Assert(!IsReadOnly);
Debug.Assert(_properties is null, "must not be set if a property list has been initialized.");
_sourceGenDelayedPropertyInitializer = value;
}
}
private Func<JsonSerializerContext, JsonPropertyInfo[]>? _sourceGenDelayedPropertyInitializer;
private JsonPropertyInfoList? _properties;
/// <summary>
/// Gets or sets a configuration object specifying polymorphism metadata.
/// </summary>
/// <exception cref="ArgumentException">
/// <paramref name="value" /> has been associated with a different <see cref="JsonTypeInfo"/> instance.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Polymorphic serialization is not supported for the current metadata <see cref="Kind"/>.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the configuration of this setting will be mapped from any <see cref="JsonDerivedTypeAttribute"/> or <see cref="JsonPolymorphicAttribute"/> annotations.
/// </remarks>
public JsonPolymorphismOptions? PolymorphismOptions
{
get => _polymorphismOptions;
set
{
VerifyMutable();
if (value != null)
{
if (Kind == JsonTypeInfoKind.None)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
if (value.DeclaringTypeInfo != null && value.DeclaringTypeInfo != this)
{
ThrowHelper.ThrowArgumentException_JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo(nameof(value));
}
value.DeclaringTypeInfo = this;
}
_polymorphismOptions = value;
}
}
/// <summary>
/// Specifies whether the current instance has been locked for modification.
/// </summary>
/// <remarks>
/// A <see cref="JsonTypeInfo"/> instance can be locked either if
/// it has been passed to one of the <see cref="JsonSerializer"/> methods,
/// has been associated with a <see cref="JsonSerializerContext"/> instance,
/// or a user explicitly called the <see cref="MakeReadOnly"/> method on the instance.
/// </remarks>
public bool IsReadOnly { get; private set; }
/// <summary>
/// Locks the current instance for further modification.
/// </summary>
/// <remarks>This method is idempotent.</remarks>
public void MakeReadOnly() => IsReadOnly = true;
private protected JsonPolymorphismOptions? _polymorphismOptions;
internal object? CreateObjectWithArgs { get; set; }
// Add method delegate for non-generic Stack and Queue; and types that derive from them.
internal object? AddMethodDelegate { get; set; }
internal JsonPropertyInfo? ExtensionDataProperty { get; private set; }
internal PolymorphicTypeResolver? PolymorphicTypeResolver { get; private set; }
// Indicates that SerializeHandler is populated.
internal bool HasSerializeHandler { get; private protected set; }
// Indicates that SerializeHandler is populated and is compatible with the associated contract metadata.
internal bool CanUseSerializeHandler { get; private set; }
// Configure would normally have thrown why initializing properties for source gen but type had SerializeHandler
// so it is allowed to be used for fast-path serialization but it will throw if used for metadata-based serialization
internal bool PropertyMetadataSerializationNotSupported { get; set; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ValidateCanBeUsedForPropertyMetadataSerialization()
{
if (PropertyMetadataSerializationNotSupported)
{
ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type);
}
}
internal Type? ElementType { get; }
internal Type? KeyType { get; }
/// <summary>
/// Return the JsonTypeInfo for the element type, or null if the type is not an enumerable or dictionary.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal JsonTypeInfo? ElementTypeInfo
{
get
{
Debug.Assert(IsConfigured);
Debug.Assert(_elementTypeInfo is null or { IsConfigurationStarted: true });
// Even though this instance has already been configured,
// it is possible for contending threads to call the property
// while the wider JsonTypeInfo graph is still being configured.
// Call EnsureConfigured() to force synchronization if necessary.
JsonTypeInfo? elementTypeInfo = _elementTypeInfo;
elementTypeInfo?.EnsureConfigured();
return elementTypeInfo;
}
set
{
Debug.Assert(!IsReadOnly);
Debug.Assert(value is null || value.Type == ElementType);
_elementTypeInfo = value;
}
}
/// <summary>
/// Return the JsonTypeInfo for the key type, or null if the type is not a dictionary.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal JsonTypeInfo? KeyTypeInfo
{
get
{
Debug.Assert(IsConfigured);
Debug.Assert(_keyTypeInfo is null or { IsConfigurationStarted: true });
// Even though this instance has already been configured,
// it is possible for contending threads to call the property
// while the wider JsonTypeInfo graph is still being configured.
// Call EnsureConfigured() to force synchronization if necessary.
JsonTypeInfo? keyTypeInfo = _keyTypeInfo;
keyTypeInfo?.EnsureConfigured();
return keyTypeInfo;
}
set
{
Debug.Assert(!IsReadOnly);
Debug.Assert(value is null || value.Type == KeyType);
_keyTypeInfo = value;
}
}
private JsonTypeInfo? _elementTypeInfo;
private JsonTypeInfo? _keyTypeInfo;
/// <summary>
/// Gets the <see cref="JsonSerializerOptions"/> value associated with the current <see cref="JsonTypeInfo" /> instance.
/// </summary>
public JsonSerializerOptions Options { get; }
/// <summary>
/// Gets the <see cref="Type"/> for which the JSON serialization contract is being defined.
/// </summary>
public Type Type { get; }
/// <summary>
/// Gets the <see cref="JsonConverter"/> associated with the current type.
/// </summary>
/// <remarks>
/// The <see cref="JsonConverter"/> associated with the type determines the value of <see cref="Kind"/>,
/// and by extension the types of metadata that are configurable in the current JSON contract.
/// As such, the value of the converter cannot be changed once a <see cref="JsonTypeInfo"/> instance has been created.
/// </remarks>
public JsonConverter Converter { get; }
/// <summary>
/// Determines the kind of contract metadata that the current instance is specifying.
/// </summary>
/// <remarks>
/// The value of <see cref="Kind"/> determines what aspects of the JSON contract are configurable.
/// For example, it is only possible to configure the <see cref="Properties"/> list for metadata
/// of kind <see cref="JsonTypeInfoKind.Object"/>.
///
/// The value of <see cref="Kind"/> is determined exclusively by the <see cref="JsonConverter"/>
/// resolved for the current type, and cannot be changed once resolution has happened.
/// User-defined custom converters (specified either via <see cref="JsonConverterAttribute"/> or <see cref="JsonSerializerOptions.Converters"/>)
/// are metadata-agnostic and thus always resolve to <see cref="JsonTypeInfoKind.None"/>.
/// </remarks>
public JsonTypeInfoKind Kind { get; private set; }
/// <summary>
/// Dummy <see cref="JsonPropertyInfo"/> instance corresponding to the declaring type of this <see cref="JsonTypeInfo"/>.
/// </summary>
/// <remarks>
/// Used as convenience in cases where we want to serialize property-like values that do not define property metadata, such as:
/// 1. a collection element type,
/// 2. a dictionary key or value type or,
/// 3. the property metadata for the root-level value.
/// For example, for a property returning <see cref="List{T}"/> where T is a string,
/// a JsonTypeInfo will be created with .Type=typeof(string) and .PropertyInfoForTypeInfo=JsonPropertyInfo{string}.
/// </remarks>
internal JsonPropertyInfo PropertyInfoForTypeInfo { get; }
private protected abstract JsonPropertyInfo CreatePropertyInfoForTypeInfo();
/// <summary>
/// Gets or sets the type-level <see cref="JsonSerializerOptions.NumberHandling"/> override.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Specified an invalid <see cref="JsonNumberHandling"/> value.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from any <see cref="JsonNumberHandlingAttribute"/> annotations.
/// </remarks>
public JsonNumberHandling? NumberHandling
{
get => _numberHandling;
set
{
VerifyMutable();
if (value is not null && !JsonSerializer.IsValidNumberHandlingValue(value.Value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_numberHandling = value;
}
}
private JsonNumberHandling? _numberHandling;
/// <summary>
/// Gets or sets the type-level <see cref="JsonUnmappedMemberHandling"/> override.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Unmapped member handling only supported for <see cref="JsonTypeInfoKind.Object"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Specified an invalid <see cref="JsonUnmappedMemberHandling"/> value.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from any <see cref="JsonUnmappedMemberHandlingAttribute"/> annotations.
/// </remarks>
public JsonUnmappedMemberHandling? UnmappedMemberHandling
{
get => _unmappedMemberHandling;
set
{
VerifyMutable();
if (Kind != JsonTypeInfoKind.Object)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
if (value is not null && !JsonSerializer.IsValidUnmappedMemberHandlingValue(value.Value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_unmappedMemberHandling = value;
}
}
private JsonUnmappedMemberHandling? _unmappedMemberHandling;
internal JsonUnmappedMemberHandling EffectiveUnmappedMemberHandling { get; private set; }
private JsonObjectCreationHandling? _preferredPropertyObjectCreationHandling;
/// <summary>
/// Gets or sets the preferred <see cref="JsonObjectCreationHandling"/> value for properties contained in the type.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
///
/// -or-
///
/// Unmapped member handling only supported for <see cref="JsonTypeInfoKind.Object"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Specified an invalid <see cref="JsonObjectCreationHandling"/> value.
/// </exception>
/// <remarks>
/// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext"/>,
/// the value of this callback will be mapped from <see cref="JsonObjectCreationHandlingAttribute"/> annotations on types.
/// </remarks>
public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling
{
get => _preferredPropertyObjectCreationHandling;
set
{
VerifyMutable();
if (Kind != JsonTypeInfoKind.Object)
{
ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind);
}
if (value is not null && !JsonSerializer.IsValidCreationHandlingValue(value.Value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_preferredPropertyObjectCreationHandling = value;
}
}
/// <summary>
/// Gets or sets the <see cref="IJsonTypeInfoResolver"/> from which this metadata instance originated.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The <see cref="JsonTypeInfo"/> instance has been locked for further modification.
/// </exception>
/// <remarks>
/// Metadata used to determine the <see cref="JsonSerializerContext.GeneratedSerializerOptions"/>
/// configuration for the current metadata instance.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public IJsonTypeInfoResolver? OriginatingResolver
{
get => _originatingResolver;
set
{
VerifyMutable();
if (value is JsonSerializerContext)
{
// The source generator uses this property setter to brand the metadata instance as user-unmodified.
// Even though users could call the same property setter to unset this flag, this is generally speaking fine.
// This flag is only used to determine fast-path invalidation, worst case scenario this would lead to a false negative.
IsCustomized = false;
}
_originatingResolver = value;
}
}
private IJsonTypeInfoResolver? _originatingResolver;
internal void VerifyMutable()
{
if (IsReadOnly)
{
ThrowHelper.ThrowInvalidOperationException_TypeInfoImmutable();
}
IsCustomized = true;
}
/// <summary>
/// Indicates that the current JsonTypeInfo might contain user modifications.
/// Defaults to true, and is only unset by the built-in contract resolvers.
/// </summary>
internal bool IsCustomized { get; set; } = true;
internal bool IsConfigured => _configurationState == ConfigurationState.Configured;
internal bool IsConfigurationStarted => _configurationState is not ConfigurationState.NotConfigured;
private volatile ConfigurationState _configurationState;
private enum ConfigurationState : byte
{
NotConfigured = 0,
Configuring = 1,
Configured = 2
};
private ExceptionDispatchInfo? _cachedConfigureError;
internal void EnsureConfigured()
{
if (!IsConfigured)
ConfigureSynchronized();
void ConfigureSynchronized()
{
Options.MakeReadOnly();
MakeReadOnly();
_cachedConfigureError?.Throw();
lock (Options.CacheContext)
{
if (_configurationState != ConfigurationState.NotConfigured)
{
// The value of _configurationState is either
// 'Configuring': recursive instance configured by this thread or
// 'Configured' : instance already configured by another thread.
// We can safely yield the configuration operation in both cases.
return;
}
_cachedConfigureError?.Throw();
try
{
_configurationState = ConfigurationState.Configuring;
Configure();
_configurationState = ConfigurationState.Configured;
}
catch (Exception e)
{
_cachedConfigureError = ExceptionDispatchInfo.Capture(e);
_configurationState = ConfigurationState.NotConfigured;
throw;
}
}
}
}
private void Configure()
{
Debug.Assert(Monitor.IsEntered(Options.CacheContext), "Configure called directly, use EnsureConfigured which synchronizes access to this method");
Debug.Assert(Options.IsReadOnly);
Debug.Assert(IsReadOnly);
PropertyInfoForTypeInfo.Configure();
if (PolymorphismOptions != null)
{
// This needs to be done before ConfigureProperties() is called
// JsonPropertyInfo.Configure() must have this value available in order to detect Polymoprhic + cyclic class case
PolymorphicTypeResolver = new PolymorphicTypeResolver(Options, PolymorphismOptions, Type, Converter.CanHaveMetadata);
}
if (Kind == JsonTypeInfoKind.Object)
{
ConfigureProperties();
if (DetermineUsesParameterizedConstructor())
{
ConfigureConstructorParameters();
}
}
if (ElementType != null)
{
_elementTypeInfo ??= Options.GetTypeInfoInternal(ElementType);
_elementTypeInfo.EnsureConfigured();
}
if (KeyType != null)
{
_keyTypeInfo ??= Options.GetTypeInfoInternal(KeyType);
_keyTypeInfo.EnsureConfigured();
}
DetermineIsCompatibleWithCurrentOptions();
CanUseSerializeHandler = HasSerializeHandler && IsCompatibleWithCurrentOptions;
}
/// <summary>
/// Gets any ancestor polymorphic types that declare
/// a type discriminator for the current type. Consulted
/// when serializing polymorphic values as objects.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal JsonTypeInfo? AncestorPolymorphicType
{
get
{
Debug.Assert(IsConfigured);
Debug.Assert(Type != typeof(object));
if (!_isAncestorPolymorphicTypeResolved)
{
_ancestorPolymorhicType = PolymorphicTypeResolver.FindNearestPolymorphicBaseType(this);
_isAncestorPolymorphicTypeResolved = true;
}
return _ancestorPolymorhicType;
}
}
private JsonTypeInfo? _ancestorPolymorhicType;
private volatile bool _isAncestorPolymorphicTypeResolved;
/// <summary>
/// Determines if the transitive closure of all JsonTypeInfo metadata referenced
/// by the current type (property types, key types, element types, ...) are
/// compatible with the settings as specified in JsonSerializerOptions.
/// </summary>
private void DetermineIsCompatibleWithCurrentOptions()
{
// Defines a recursive algorithm validating that the `IsCurrentNodeCompatible`
// predicate is valid for every node in the type graph. This method only checks
// the immediate children, with recursion being driven by the Configure() method.
// Therefore, this method must be called _after_ the child nodes have been configured.
Debug.Assert(IsReadOnly);
Debug.Assert(!IsConfigured);
if (!IsCurrentNodeCompatible())
{
IsCompatibleWithCurrentOptions = false;
return;
}
if (_properties != null)
{
foreach (JsonPropertyInfo property in _properties)
{
Debug.Assert(property.IsConfigured);
if (!property.IsPropertyTypeInfoConfigured)
{
// Either an ignored property or property is part of a cycle.
// In both cases we can ignore these instances.
continue;
}
if (!property.JsonTypeInfo.IsCompatibleWithCurrentOptions)
{
IsCompatibleWithCurrentOptions = false;
return;
}
}
}
if (_elementTypeInfo?.IsCompatibleWithCurrentOptions == false ||
_keyTypeInfo?.IsCompatibleWithCurrentOptions == false)
{
IsCompatibleWithCurrentOptions = false;
return;
}
Debug.Assert(IsCompatibleWithCurrentOptions);
// Defines the core predicate that must be checked for every node in the type graph.
bool IsCurrentNodeCompatible()
{
if (Options.CanUseFastPathSerializationLogic)
{
// Simple case/backward compatibility: options uses a combination of compatible built-in converters.
return true;
}
if (IsCustomized)
{
// Return false if we have detected contract customization by the user.
return false;
}
return OriginatingResolver.IsCompatibleWithOptions(Options);
}
}
/// <summary>
/// Holds the result of the above algorithm -- NB must default to true
/// to establish a base case for recursive types and any JsonIgnored property types.
/// </summary>
private bool IsCompatibleWithCurrentOptions { get; set; } = true;
/// <summary>
/// Determine if the current configuration is compatible with using a parameterized constructor.
/// </summary>
internal bool DetermineUsesParameterizedConstructor()
=> Converter.ConstructorIsParameterized && CreateObject is null;
#if DEBUG
internal string GetPropertyDebugInfo(ReadOnlySpan<byte> unescapedPropertyName)
{
string propertyName = JsonHelpers.Utf8GetString(unescapedPropertyName);
return $"propertyName = {propertyName}; DebugInfo={GetDebugInfo()}";
}
internal string GetDebugInfo()
{
ConverterStrategy converterStrategy = Converter.ConverterStrategy;
string jtiTypeName = GetType().Name;
string typeName = Type.FullName!;
bool propCacheInitialized = PropertyCache != null;
StringBuilder sb = new();
sb.AppendLine("{");
sb.AppendLine($" GetType: {jtiTypeName},");
sb.AppendLine($" Type: {typeName},");
sb.AppendLine($" ConverterStrategy: {converterStrategy},");
sb.AppendLine($" IsConfigured: {IsConfigured},");
sb.AppendLine($" HasPropertyCache: {propCacheInitialized},");
if (propCacheInitialized)
{
sb.AppendLine(" Properties: {");
foreach (JsonPropertyInfo pi in PropertyCache!.Values)
{
sb.AppendLine($" {pi.Name}:");
sb.AppendLine($"{pi.GetDebugInfo(indent: 6)},");
}
sb.AppendLine(" },");
}
sb.AppendLine("}");
return sb.ToString();
}
#endif
/// <summary>
/// Creates a blank <see cref="JsonTypeInfo{T}"/> instance.
/// </summary>
/// <typeparam name="T">The type for which contract metadata is specified.</typeparam>
/// <param name="options">The <see cref="JsonSerializerOptions"/> instance the metadata is associated with.</param>
/// <returns>A blank <see cref="JsonTypeInfo{T}"/> instance.</returns>
/// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception>
/// <remarks>
/// The returned <see cref="JsonTypeInfo{T}"/> will be blank, with the exception of the
/// <see cref="Converter"/> property which will be resolved either from
/// <see cref="JsonSerializerOptions.Converters"/> or the built-in converters for the type.
/// Any converters specified via <see cref="JsonConverterAttribute"/> on the type declaration
/// will not be resolved by this method.
///
/// What converter does get resolved influences the value of <see cref="Kind"/>,
/// which constrains the type of metadata that can be modified in the <see cref="JsonTypeInfo"/> instance.
/// </remarks>
[RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)]
[RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)]
public static JsonTypeInfo<T> CreateJsonTypeInfo<T>(JsonSerializerOptions options)
{
if (options == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(options));
}
JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(typeof(T), options, resolveJsonConverterAttribute: false);
return new JsonTypeInfo<T>(converter, options);
}
/// <summary>
/// Creates a blank <see cref="JsonTypeInfo"/> instance.
/// </summary>
/// <param name="type">The type for which contract metadata is specified.</param>
/// <param name="options">The <see cref="JsonSerializerOptions"/> instance the metadata is associated with.</param>
/// <returns>A blank <see cref="JsonTypeInfo"/> instance.</returns>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="options"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="type"/> cannot be used for serialization.</exception>
/// <remarks>
/// The returned <see cref="JsonTypeInfo"/> will be blank, with the exception of the
/// <see cref="Converter"/> property which will be resolved either from
/// <see cref="JsonSerializerOptions.Converters"/> or the built-in converters for the type.
/// Any converters specified via <see cref="JsonConverterAttribute"/> on the type declaration
/// will not be resolved by this method.
///
/// What converter does get resolved influences the value of <see cref="Kind"/>,
/// which constrains the type of metadata that can be modified in the <see cref="JsonTypeInfo"/> instance.
/// </remarks>
[RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)]
[RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)]
public static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options)
{
if (type == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(type));
}
if (options == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(options));
}
if (IsInvalidForSerialization(type))
{
ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(type), type, null, null);
}
JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(type, options, resolveJsonConverterAttribute: false);
return CreateJsonTypeInfo(type, converter, options);
}
[RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)]
[RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)]
internal static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options)
{
JsonTypeInfo jsonTypeInfo;
if (converter.Type == type)
{
// For performance, avoid doing a reflection-based instantiation
// if the converter type matches that of the declared type.
jsonTypeInfo = converter.CreateJsonTypeInfo(options);
}
else
{
Type jsonTypeInfoType = typeof(JsonTypeInfo<>).MakeGenericType(type);
jsonTypeInfo = (JsonTypeInfo)jsonTypeInfoType.CreateInstanceNoWrapExceptions(
parameterTypes: new Type[] { typeof(JsonConverter), typeof(JsonSerializerOptions) },
parameters: new object[] { converter, options })!;
}
Debug.Assert(jsonTypeInfo.Type == type);
return jsonTypeInfo;
}
/// <summary>
/// Creates a blank <see cref="JsonPropertyInfo"/> instance for the current <see cref="JsonTypeInfo"/>.
/// </summary>
/// <param name="propertyType">The declared type for the property.</param>
/// <param name="name">The property name used in JSON serialization and deserialization.</param>
/// <returns>A blank <see cref="JsonPropertyInfo"/> instance.</returns>
/// <exception cref="ArgumentNullException"><paramref name="propertyType"/> or <paramref name="name"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="propertyType"/> cannot be used for serialization.</exception>
/// <exception cref="InvalidOperationException">The <see cref="JsonTypeInfo"/> instance has been locked for further modification.</exception>
[RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)]
[RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)]
public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name)
{
if (propertyType == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(propertyType));
}
if (name == null)
{
ThrowHelper.ThrowArgumentNullException(nameof(name));
}
if (IsInvalidForSerialization(propertyType))
{
ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(propertyType), propertyType, Type, name);
}
VerifyMutable();
JsonPropertyInfo propertyInfo = CreatePropertyUsingReflection(propertyType, declaringType: null);
propertyInfo.Name = name;
return propertyInfo;
}
internal JsonParameterInfoValues[]? ParameterInfoValues { get; set; }
// Untyped, root-level serialization methods
internal abstract void SerializeAsObject(Utf8JsonWriter writer, object? rootValue);
internal abstract Task SerializeAsObjectAsync(Stream utf8Json, object? rootValue, CancellationToken cancellationToken);
internal abstract void SerializeAsObject(Stream utf8Json, object? rootValue);
// Untyped, root-level deserialization methods
internal abstract object? DeserializeAsObject(ref Utf8JsonReader reader, ref ReadStack state);
internal abstract ValueTask<object?> DeserializeAsObjectAsync(Stream utf8Json, CancellationToken cancellationToken);
internal abstract object? DeserializeAsObject(Stream utf8Json);
internal ref struct PropertyHierarchyResolutionState(JsonSerializerOptions options)