| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.ComponentModel; |
| | | 7 | | using System.Diagnostics; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using System.IO; |
| | | 10 | | using System.IO.Pipelines; |
| | | 11 | | using System.Reflection; |
| | | 12 | | using System.Runtime.CompilerServices; |
| | | 13 | | using System.Runtime.ExceptionServices; |
| | | 14 | | using System.Text.Json.Reflection; |
| | | 15 | | using System.Text.Json.Serialization.Converters; |
| | | 16 | | using System.Threading; |
| | | 17 | | using System.Threading.Tasks; |
| | | 18 | | |
| | | 19 | | namespace System.Text.Json.Serialization.Metadata |
| | | 20 | | { |
| | | 21 | | /// <summary> |
| | | 22 | | /// Provides JSON serialization-related metadata about a type. |
| | | 23 | | /// </summary> |
| | | 24 | | [DebuggerDisplay("{DebuggerDisplay,nq}")] |
| | | 25 | | public abstract partial class JsonTypeInfo |
| | | 26 | | { |
| | | 27 | | internal const string MetadataFactoryRequiresUnreferencedCode = "JSON serialization and deserialization might re |
| | | 28 | | |
| | | 29 | | internal const string JsonObjectTypeName = "System.Text.Json.Nodes.JsonObject"; |
| | | 30 | | |
| | | 31 | | internal delegate T ParameterizedConstructorDelegate<T, TArg0, TArg1, TArg2, TArg3>(TArg0? arg0, TArg1? arg1, TA |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Negated bitmask of the required properties, indexed by <see cref="JsonPropertyInfo.PropertyIndex"/>. |
| | | 35 | | /// </summary> |
| | 1329 | 36 | | internal BitArray? OptionalPropertiesMask { get; private set; } |
| | 30 | 37 | | internal bool ShouldTrackRequiredProperties => OptionalPropertiesMask is not null; |
| | | 38 | | |
| | | 39 | | private Action<object>? _onSerializing; |
| | | 40 | | private Action<object>? _onSerialized; |
| | | 41 | | private Action<object>? _onDeserializing; |
| | | 42 | | private Action<object>? _onDeserialized; |
| | | 43 | | |
| | 12254 | 44 | | internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options) |
| | 12254 | 45 | | { |
| | 12254 | 46 | | Type = type; |
| | 12254 | 47 | | Options = options; |
| | 12254 | 48 | | Converter = converter; |
| | 12254 | 49 | | Kind = GetTypeInfoKind(type, converter); |
| | 12254 | 50 | | PropertyInfoForTypeInfo = CreatePropertyInfoForTypeInfo(); |
| | 12254 | 51 | | ElementType = converter.ElementType; |
| | 12254 | 52 | | KeyType = converter.KeyType; |
| | 12254 | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Gets the element type corresponding to an enumerable, dictionary or optional type. |
| | | 57 | | /// </summary> |
| | | 58 | | /// <remarks> |
| | | 59 | | /// Returns the element type for enumerable types, the value type for dictionary types, |
| | | 60 | | /// and the underlying type for <see cref="Nullable{T}"/> or F# optional types. |
| | | 61 | | /// |
| | | 62 | | /// Returns <see langword="null"/> for all other types or types using custom converters. |
| | | 63 | | /// </remarks> |
| | 13256 | 64 | | public Type? ElementType { get; } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Gets the key type corresponding to a dictionary type. |
| | | 68 | | /// </summary> |
| | | 69 | | /// <remarks> |
| | | 70 | | /// Returns the key type for dictionary types. |
| | | 71 | | /// |
| | | 72 | | /// Returns <see langword="null"/> for all other types or types using custom converters. |
| | | 73 | | /// </remarks> |
| | 12618 | 74 | | public Type? KeyType { get; } |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Gets or sets a parameterless factory to be used on deserialization. |
| | | 78 | | /// </summary> |
| | | 79 | | /// <exception cref="InvalidOperationException"> |
| | | 80 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 81 | | /// |
| | | 82 | | /// -or- |
| | | 83 | | /// |
| | | 84 | | /// A parameterless factory is not supported for the current metadata <see cref="Kind"/>. |
| | | 85 | | /// </exception> |
| | | 86 | | /// <remarks> |
| | | 87 | | /// If set to <see langword="null" />, any attempt to deserialize instances of the given type will result in an |
| | | 88 | | /// |
| | | 89 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 90 | | /// types with a single default constructor or default constructors annotated with <see cref="JsonConstructorAtt |
| | | 91 | | /// will be mapped to this delegate. |
| | | 92 | | /// </remarks> |
| | | 93 | | public Func<object>? CreateObject |
| | | 94 | | { |
| | 7329 | 95 | | get => _createObject; |
| | | 96 | | set |
| | 0 | 97 | | { |
| | 0 | 98 | | SetCreateObject(value); |
| | 0 | 99 | | } |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | private protected abstract void SetCreateObject(Delegate? createObject); |
| | | 103 | | private protected Func<object>? _createObject; |
| | | 104 | | |
| | 12523 | 105 | | internal Func<object>? CreateObjectForExtensionDataProperty { get; set; } |
| | | 106 | | |
| | | 107 | | /// <summary> |
| | | 108 | | /// Gets or sets a callback to be invoked before serialization occurs. |
| | | 109 | | /// </summary> |
| | | 110 | | /// <exception cref="InvalidOperationException"> |
| | | 111 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 112 | | /// |
| | | 113 | | /// -or- |
| | | 114 | | /// |
| | | 115 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 116 | | /// </exception> |
| | | 117 | | /// <remarks> |
| | | 118 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 119 | | /// the value of this callback will be mapped from any <see cref="IJsonOnSerializing"/> implementation on the ty |
| | | 120 | | /// </remarks> |
| | | 121 | | public Action<object>? OnSerializing |
| | | 122 | | { |
| | 0 | 123 | | get => _onSerializing; |
| | | 124 | | set |
| | 0 | 125 | | { |
| | 0 | 126 | | VerifyMutable(); |
| | | 127 | | |
| | 0 | 128 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 129 | | { |
| | 0 | 130 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 131 | | } |
| | | 132 | | |
| | 0 | 133 | | _onSerializing = value; |
| | 0 | 134 | | } |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Gets or sets a callback to be invoked after serialization occurs. |
| | | 139 | | /// </summary> |
| | | 140 | | /// <exception cref="InvalidOperationException"> |
| | | 141 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 142 | | /// |
| | | 143 | | /// -or- |
| | | 144 | | /// |
| | | 145 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 146 | | /// </exception> |
| | | 147 | | /// <remarks> |
| | | 148 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 149 | | /// the value of this callback will be mapped from any <see cref="IJsonOnSerialized"/> implementation on the typ |
| | | 150 | | /// </remarks> |
| | | 151 | | public Action<object>? OnSerialized |
| | | 152 | | { |
| | 0 | 153 | | get => _onSerialized; |
| | | 154 | | set |
| | 0 | 155 | | { |
| | 0 | 156 | | VerifyMutable(); |
| | | 157 | | |
| | 0 | 158 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 159 | | { |
| | 0 | 160 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 161 | | } |
| | | 162 | | |
| | 0 | 163 | | _onSerialized = value; |
| | 0 | 164 | | } |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | /// <summary> |
| | | 168 | | /// Gets or sets a callback to be invoked before deserialization occurs. |
| | | 169 | | /// </summary> |
| | | 170 | | /// <exception cref="InvalidOperationException"> |
| | | 171 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 172 | | /// |
| | | 173 | | /// -or- |
| | | 174 | | /// |
| | | 175 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 176 | | /// </exception> |
| | | 177 | | /// <remarks> |
| | | 178 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 179 | | /// the value of this callback will be mapped from any <see cref="IJsonOnDeserializing"/> implementation on the |
| | | 180 | | /// </remarks> |
| | | 181 | | public Action<object>? OnDeserializing |
| | | 182 | | { |
| | 294 | 183 | | get => _onDeserializing; |
| | | 184 | | set |
| | 0 | 185 | | { |
| | 0 | 186 | | VerifyMutable(); |
| | | 187 | | |
| | 0 | 188 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 189 | | { |
| | 0 | 190 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 191 | | } |
| | | 192 | | |
| | 0 | 193 | | if (Converter.IsConvertibleCollection) |
| | 0 | 194 | | { |
| | | 195 | | // The values for convertible collections aren't available at the start of deserialization. |
| | 0 | 196 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOnDeserializingCallbacksNotSupported(Type); |
| | | 197 | | } |
| | | 198 | | |
| | 0 | 199 | | _onDeserializing = value; |
| | 0 | 200 | | } |
| | | 201 | | } |
| | | 202 | | |
| | | 203 | | /// <summary> |
| | | 204 | | /// Gets or sets a callback to be invoked after deserialization occurs. |
| | | 205 | | /// </summary> |
| | | 206 | | /// <exception cref="InvalidOperationException"> |
| | | 207 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 208 | | /// |
| | | 209 | | /// -or- |
| | | 210 | | /// |
| | | 211 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 212 | | /// </exception> |
| | | 213 | | /// <remarks> |
| | | 214 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 215 | | /// the value of this callback will be mapped from any <see cref="IJsonOnDeserialized"/> implementation on the t |
| | | 216 | | /// </remarks> |
| | | 217 | | public Action<object>? OnDeserialized |
| | | 218 | | { |
| | 34 | 219 | | get => _onDeserialized; |
| | | 220 | | set |
| | 0 | 221 | | { |
| | 0 | 222 | | VerifyMutable(); |
| | | 223 | | |
| | 0 | 224 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 225 | | { |
| | 0 | 226 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 227 | | } |
| | | 228 | | |
| | 0 | 229 | | _onDeserialized = value; |
| | 0 | 230 | | } |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary> |
| | | 234 | | /// Gets the list of <see cref="JsonPropertyInfo"/> metadata corresponding to the current type. |
| | | 235 | | /// </summary> |
| | | 236 | | /// <remarks> |
| | | 237 | | /// Property is only applicable to metadata of kind <see cref="JsonTypeInfoKind.Object"/>. |
| | | 238 | | /// For other kinds an empty, read-only list will be returned. |
| | | 239 | | /// |
| | | 240 | | /// The order of <see cref="JsonPropertyInfo"/> entries in the list determines the serialization order, |
| | | 241 | | /// unless either of the entries specifies a non-zero <see cref="JsonPropertyInfo.Order"/> value, |
| | | 242 | | /// in which case the properties will be stable sorted by <see cref="JsonPropertyInfo.Order"/>. |
| | | 243 | | /// |
| | | 244 | | /// It is required that added <see cref="JsonPropertyInfo"/> entries are unique up to <see cref="JsonPropertyInf |
| | | 245 | | /// however this will only be validated on serialization, once the metadata instance gets locked for further mod |
| | | 246 | | /// </remarks> |
| | 0 | 247 | | public IList<JsonPropertyInfo> Properties => PropertyList; |
| | | 248 | | |
| | | 249 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 250 | | internal JsonPropertyInfoList PropertyList |
| | | 251 | | { |
| | | 252 | | get |
| | 9093 | 253 | | { |
| | 9093 | 254 | | return _properties ?? CreatePropertyList(); |
| | | 255 | | JsonPropertyInfoList CreatePropertyList() |
| | 1299 | 256 | | { |
| | 1299 | 257 | | var list = new JsonPropertyInfoList(this); |
| | 1299 | 258 | | if (_sourceGenDelayedPropertyInitializer is { } propInit) |
| | 0 | 259 | | { |
| | | 260 | | // .NET 6 source gen backward compatibility -- ensure that the |
| | | 261 | | // property initializer delegate is invoked lazily. |
| | 0 | 262 | | JsonMetadataServices.PopulateProperties(this, list, propInit); |
| | 0 | 263 | | } |
| | | 264 | | |
| | 1299 | 265 | | JsonPropertyInfoList? result = Interlocked.CompareExchange(ref _properties, list, null); |
| | 1299 | 266 | | _sourceGenDelayedPropertyInitializer = null; |
| | 1299 | 267 | | return result ?? list; |
| | 1299 | 268 | | } |
| | 9093 | 269 | | } |
| | | 270 | | } |
| | | 271 | | |
| | | 272 | | /// <summary> |
| | | 273 | | /// Stores the .NET 6-style property initialization delegate for delayed evaluation. |
| | | 274 | | /// </summary> |
| | | 275 | | internal Func<JsonSerializerContext, JsonPropertyInfo[]>? SourceGenDelayedPropertyInitializer |
| | | 276 | | { |
| | | 277 | | get => _sourceGenDelayedPropertyInitializer; |
| | | 278 | | set |
| | 0 | 279 | | { |
| | 0 | 280 | | Debug.Assert(!IsReadOnly); |
| | 0 | 281 | | Debug.Assert(_properties is null, "must not be set if a property list has been initialized."); |
| | 0 | 282 | | _sourceGenDelayedPropertyInitializer = value; |
| | 0 | 283 | | } |
| | | 284 | | } |
| | | 285 | | |
| | | 286 | | private Func<JsonSerializerContext, JsonPropertyInfo[]>? _sourceGenDelayedPropertyInitializer; |
| | | 287 | | private JsonPropertyInfoList? _properties; |
| | | 288 | | |
| | | 289 | | /// <summary> |
| | | 290 | | /// Gets or sets a configuration object specifying polymorphism metadata. |
| | | 291 | | /// </summary> |
| | | 292 | | /// <exception cref="ArgumentException"> |
| | | 293 | | /// <paramref name="value" /> has been associated with a different <see cref="JsonTypeInfo"/> instance. |
| | | 294 | | /// </exception> |
| | | 295 | | /// <exception cref="InvalidOperationException"> |
| | | 296 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 297 | | /// |
| | | 298 | | /// -or- |
| | | 299 | | /// |
| | | 300 | | /// Polymorphic serialization is not supported for the current metadata <see cref="Kind"/>. |
| | | 301 | | /// </exception> |
| | | 302 | | /// <remarks> |
| | | 303 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 304 | | /// the configuration of this setting will be mapped from any <see cref="JsonDerivedTypeAttribute"/> or <see cre |
| | | 305 | | /// </remarks> |
| | | 306 | | public JsonPolymorphismOptions? PolymorphismOptions |
| | | 307 | | { |
| | 12254 | 308 | | get => _polymorphismOptions; |
| | | 309 | | set |
| | 0 | 310 | | { |
| | 0 | 311 | | VerifyMutable(); |
| | | 312 | | |
| | 0 | 313 | | if (value != null) |
| | 0 | 314 | | { |
| | 0 | 315 | | if (Kind == JsonTypeInfoKind.None) |
| | 0 | 316 | | { |
| | 0 | 317 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 318 | | } |
| | | 319 | | |
| | 0 | 320 | | if (value.DeclaringTypeInfo != null && value.DeclaringTypeInfo != this) |
| | 0 | 321 | | { |
| | 0 | 322 | | ThrowHelper.ThrowArgumentException_JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo(na |
| | | 323 | | } |
| | | 324 | | |
| | 0 | 325 | | value.DeclaringTypeInfo = this; |
| | 0 | 326 | | } |
| | | 327 | | |
| | 0 | 328 | | _polymorphismOptions = value; |
| | 0 | 329 | | } |
| | | 330 | | } |
| | | 331 | | |
| | | 332 | | /// <summary> |
| | | 333 | | /// Specifies whether the current instance has been locked for modification. |
| | | 334 | | /// </summary> |
| | | 335 | | /// <remarks> |
| | | 336 | | /// A <see cref="JsonTypeInfo"/> instance can be locked either if |
| | | 337 | | /// it has been passed to one of the <see cref="JsonSerializer"/> methods, |
| | | 338 | | /// has been associated with a <see cref="JsonSerializerContext"/> instance, |
| | | 339 | | /// or a user explicitly called the <see cref="MakeReadOnly"/> method on the instance. |
| | | 340 | | /// </remarks> |
| | 180499 | 341 | | public bool IsReadOnly { get; private set; } |
| | | 342 | | |
| | | 343 | | /// <summary> |
| | | 344 | | /// Locks the current instance for further modification. |
| | | 345 | | /// </summary> |
| | | 346 | | /// <remarks>This method is idempotent.</remarks> |
| | 24508 | 347 | | public void MakeReadOnly() => IsReadOnly = true; |
| | | 348 | | |
| | | 349 | | private protected JsonPolymorphismOptions? _polymorphismOptions; |
| | | 350 | | |
| | 10095 | 351 | | internal object? CreateObjectWithArgs { get; set; } |
| | | 352 | | |
| | | 353 | | // Add method delegate for non-generic Stack and Queue; and types that derive from them. |
| | 0 | 354 | | internal object? AddMethodDelegate { get; set; } |
| | | 355 | | |
| | 3347 | 356 | | internal JsonPropertyInfo? ExtensionDataProperty { get; private set; } |
| | | 357 | | |
| | 55928 | 358 | | internal PolymorphicTypeResolver? PolymorphicTypeResolver { get; private set; } |
| | | 359 | | |
| | | 360 | | // Indicates that SerializeHandler is populated. |
| | 12254 | 361 | | internal bool HasSerializeHandler { get; private protected set; } |
| | | 362 | | |
| | | 363 | | // Indicates that SerializeHandler is populated and is compatible with the associated contract metadata. |
| | 12254 | 364 | | internal bool CanUseSerializeHandler { get; private set; } |
| | | 365 | | |
| | | 366 | | // Configure would normally have thrown why initializing properties for source gen but type had SerializeHandler |
| | | 367 | | // so it is allowed to be used for fast-path serialization but it will throw if used for metadata-based serializ |
| | 8 | 368 | | internal bool PropertyMetadataSerializationNotSupported { get; set; } |
| | | 369 | | |
| | 1299 | 370 | | internal bool IsNullable => Converter.NullableElementConverter is not null; |
| | | 371 | | internal bool CanBeNull => PropertyInfoForTypeInfo.PropertyTypeCanBeNull; |
| | | 372 | | |
| | | 373 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 374 | | internal void ValidateCanBeUsedForPropertyMetadataSerialization() |
| | 8 | 375 | | { |
| | 8 | 376 | | if (PropertyMetadataSerializationNotSupported) |
| | 0 | 377 | | { |
| | 0 | 378 | | ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type); |
| | | 379 | | } |
| | 8 | 380 | | } |
| | | 381 | | |
| | | 382 | | /// <summary> |
| | | 383 | | /// Return the JsonTypeInfo for the element type, or null if the type is not an enumerable or dictionary. |
| | | 384 | | /// </summary> |
| | | 385 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 386 | | internal JsonTypeInfo? ElementTypeInfo |
| | | 387 | | { |
| | | 388 | | get |
| | 1362 | 389 | | { |
| | 1362 | 390 | | Debug.Assert(IsConfigured); |
| | 1362 | 391 | | Debug.Assert(_elementTypeInfo is null or { IsConfigurationStarted: true }); |
| | | 392 | | // Even though this instance has already been configured, |
| | | 393 | | // it is possible for contending threads to call the property |
| | | 394 | | // while the wider JsonTypeInfo graph is still being configured. |
| | | 395 | | // Call EnsureConfigured() to force synchronization if necessary. |
| | 1362 | 396 | | JsonTypeInfo? elementTypeInfo = _elementTypeInfo; |
| | 1362 | 397 | | elementTypeInfo?.EnsureConfigured(); |
| | 1362 | 398 | | return elementTypeInfo; |
| | 1362 | 399 | | } |
| | | 400 | | set |
| | 0 | 401 | | { |
| | 0 | 402 | | Debug.Assert(!IsReadOnly); |
| | 0 | 403 | | Debug.Assert(value is null || value.Type == ElementType); |
| | 0 | 404 | | _elementTypeInfo = value; |
| | 0 | 405 | | } |
| | | 406 | | } |
| | | 407 | | |
| | | 408 | | /// <summary> |
| | | 409 | | /// Return the JsonTypeInfo for the key type, or null if the type is not a dictionary. |
| | | 410 | | /// </summary> |
| | | 411 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 412 | | internal JsonTypeInfo? KeyTypeInfo |
| | | 413 | | { |
| | | 414 | | get |
| | 650 | 415 | | { |
| | 650 | 416 | | Debug.Assert(IsConfigured); |
| | 650 | 417 | | Debug.Assert(_keyTypeInfo is null or { IsConfigurationStarted: true }); |
| | | 418 | | // Even though this instance has already been configured, |
| | | 419 | | // it is possible for contending threads to call the property |
| | | 420 | | // while the wider JsonTypeInfo graph is still being configured. |
| | | 421 | | // Call EnsureConfigured() to force synchronization if necessary. |
| | 650 | 422 | | JsonTypeInfo? keyTypeInfo = _keyTypeInfo; |
| | 650 | 423 | | keyTypeInfo?.EnsureConfigured(); |
| | 650 | 424 | | return keyTypeInfo; |
| | 650 | 425 | | } |
| | | 426 | | set |
| | 0 | 427 | | { |
| | 0 | 428 | | Debug.Assert(!IsReadOnly); |
| | 0 | 429 | | Debug.Assert(value is null || value.Type == KeyType); |
| | 0 | 430 | | _keyTypeInfo = value; |
| | 0 | 431 | | } |
| | | 432 | | } |
| | | 433 | | |
| | | 434 | | private JsonTypeInfo? _elementTypeInfo; |
| | | 435 | | private JsonTypeInfo? _keyTypeInfo; |
| | | 436 | | |
| | | 437 | | /// <summary> |
| | | 438 | | /// Gets the <see cref="JsonSerializerOptions"/> value associated with the current <see cref="JsonTypeInfo" /> i |
| | | 439 | | /// </summary> |
| | 334695 | 440 | | public JsonSerializerOptions Options { get; } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Gets the <see cref="Type"/> for which the JSON serialization contract is being defined. |
| | | 444 | | /// </summary> |
| | 186982 | 445 | | public Type Type { get; } |
| | | 446 | | |
| | | 447 | | /// <summary> |
| | | 448 | | /// Gets the <see cref="JsonConverter"/> associated with the current type. |
| | | 449 | | /// </summary> |
| | | 450 | | /// <remarks> |
| | | 451 | | /// The <see cref="JsonConverter"/> associated with the type determines the value of <see cref="Kind"/>, |
| | | 452 | | /// and by extension the types of metadata that are configurable in the current JSON contract. |
| | | 453 | | /// As such, the value of the converter cannot be changed once a <see cref="JsonTypeInfo"/> instance has been cr |
| | | 454 | | /// </remarks> |
| | 43598 | 455 | | public JsonConverter Converter { get; } |
| | | 456 | | |
| | | 457 | | /// <summary> |
| | | 458 | | /// Determines the kind of contract metadata that the current instance is specifying. |
| | | 459 | | /// </summary> |
| | | 460 | | /// <remarks> |
| | | 461 | | /// The value of <see cref="Kind"/> determines what aspects of the JSON contract are configurable. |
| | | 462 | | /// For example, it is only possible to configure the <see cref="Properties"/> list for metadata |
| | | 463 | | /// of kind <see cref="JsonTypeInfoKind.Object"/>. |
| | | 464 | | /// |
| | | 465 | | /// The value of <see cref="Kind"/> is determined exclusively by the <see cref="JsonConverter"/> |
| | | 466 | | /// resolved for the current type, and cannot be changed once resolution has happened. |
| | | 467 | | /// User-defined custom converters (specified either via <see cref="JsonConverterAttribute"/> or <see cref="Json |
| | | 468 | | /// are metadata-agnostic and thus always resolve to <see cref="JsonTypeInfoKind.None"/>. |
| | | 469 | | /// </remarks> |
| | 106961 | 470 | | public JsonTypeInfoKind Kind { get; } |
| | | 471 | | |
| | | 472 | | /// <summary> |
| | | 473 | | /// Dummy <see cref="JsonPropertyInfo"/> instance corresponding to the declaring type of this <see cref="JsonTyp |
| | | 474 | | /// </summary> |
| | | 475 | | /// <remarks> |
| | | 476 | | /// Used as convenience in cases where we want to serialize property-like values that do not define property met |
| | | 477 | | /// 1. a collection element type, |
| | | 478 | | /// 2. a dictionary key or value type or, |
| | | 479 | | /// 3. the property metadata for the root-level value. |
| | | 480 | | /// For example, for a property returning <see cref="List{T}"/> where T is a string, |
| | | 481 | | /// a JsonTypeInfo will be created with .Type=typeof(string) and .PropertyInfoForTypeInfo=JsonPropertyInfo{strin |
| | | 482 | | /// </remarks> |
| | 68394 | 483 | | internal JsonPropertyInfo PropertyInfoForTypeInfo { get; } |
| | | 484 | | |
| | | 485 | | private protected abstract JsonPropertyInfo CreatePropertyInfoForTypeInfo(); |
| | | 486 | | |
| | | 487 | | /// <summary> |
| | | 488 | | /// Gets or sets the type-level <see cref="JsonSerializerOptions.NumberHandling"/> override. |
| | | 489 | | /// </summary> |
| | | 490 | | /// <exception cref="InvalidOperationException"> |
| | | 491 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 492 | | /// </exception> |
| | | 493 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 494 | | /// Specified an invalid <see cref="JsonNumberHandling"/> value. |
| | | 495 | | /// </exception> |
| | | 496 | | /// <remarks> |
| | | 497 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 498 | | /// the value of this callback will be mapped from any <see cref="JsonNumberHandlingAttribute"/> annotations. |
| | | 499 | | /// </remarks> |
| | | 500 | | public JsonNumberHandling? NumberHandling |
| | | 501 | | { |
| | 25028 | 502 | | get => _numberHandling; |
| | | 503 | | set |
| | 0 | 504 | | { |
| | 0 | 505 | | VerifyMutable(); |
| | | 506 | | |
| | 0 | 507 | | if (value is not null && !JsonSerializer.IsValidNumberHandlingValue(value.Value)) |
| | 0 | 508 | | { |
| | 0 | 509 | | throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 510 | | } |
| | | 511 | | |
| | 0 | 512 | | _numberHandling = value; |
| | 0 | 513 | | } |
| | | 514 | | } |
| | | 515 | | |
| | 0 | 516 | | internal JsonNumberHandling EffectiveNumberHandling => _numberHandling ?? Options.NumberHandling; |
| | | 517 | | private JsonNumberHandling? _numberHandling; |
| | | 518 | | |
| | | 519 | | /// <summary> |
| | | 520 | | /// Gets or sets the type-level <see cref="JsonUnmappedMemberHandling"/> override. |
| | | 521 | | /// </summary> |
| | | 522 | | /// <exception cref="InvalidOperationException"> |
| | | 523 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 524 | | /// |
| | | 525 | | /// -or- |
| | | 526 | | /// |
| | | 527 | | /// Unmapped member handling only supported for <see cref="JsonTypeInfoKind.Object"/>. |
| | | 528 | | /// </exception> |
| | | 529 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 530 | | /// Specified an invalid <see cref="JsonUnmappedMemberHandling"/> value. |
| | | 531 | | /// </exception> |
| | | 532 | | /// <remarks> |
| | | 533 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 534 | | /// the value of this callback will be mapped from any <see cref="JsonUnmappedMemberHandlingAttribute"/> annotat |
| | | 535 | | /// </remarks> |
| | | 536 | | public JsonUnmappedMemberHandling? UnmappedMemberHandling |
| | | 537 | | { |
| | 1299 | 538 | | get => _unmappedMemberHandling; |
| | | 539 | | set |
| | 0 | 540 | | { |
| | 0 | 541 | | VerifyMutable(); |
| | | 542 | | |
| | 0 | 543 | | if (Kind != JsonTypeInfoKind.Object) |
| | 0 | 544 | | { |
| | 0 | 545 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 546 | | } |
| | | 547 | | |
| | 0 | 548 | | if (value is not null && !JsonSerializer.IsValidUnmappedMemberHandlingValue(value.Value)) |
| | 0 | 549 | | { |
| | 0 | 550 | | throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 551 | | } |
| | | 552 | | |
| | 0 | 553 | | _unmappedMemberHandling = value; |
| | 0 | 554 | | } |
| | | 555 | | } |
| | | 556 | | |
| | | 557 | | private JsonUnmappedMemberHandling? _unmappedMemberHandling; |
| | | 558 | | |
| | 1299 | 559 | | internal JsonUnmappedMemberHandling EffectiveUnmappedMemberHandling { get; private set; } |
| | | 560 | | |
| | | 561 | | private JsonObjectCreationHandling? _preferredPropertyObjectCreationHandling; |
| | | 562 | | |
| | | 563 | | /// <summary> |
| | | 564 | | /// Gets or sets the preferred <see cref="JsonObjectCreationHandling"/> value for properties contained in the ty |
| | | 565 | | /// </summary> |
| | | 566 | | /// <exception cref="InvalidOperationException"> |
| | | 567 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 568 | | /// |
| | | 569 | | /// -or- |
| | | 570 | | /// |
| | | 571 | | /// Unmapped member handling only supported for <see cref="JsonTypeInfoKind.Object"/>. |
| | | 572 | | /// </exception> |
| | | 573 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 574 | | /// Specified an invalid <see cref="JsonObjectCreationHandling"/> value. |
| | | 575 | | /// </exception> |
| | | 576 | | /// <remarks> |
| | | 577 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 578 | | /// the value of this callback will be mapped from <see cref="JsonObjectCreationHandlingAttribute"/> annotations |
| | | 579 | | /// </remarks> |
| | | 580 | | public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling |
| | | 581 | | { |
| | 20048 | 582 | | get => _preferredPropertyObjectCreationHandling; |
| | | 583 | | set |
| | 0 | 584 | | { |
| | 0 | 585 | | VerifyMutable(); |
| | | 586 | | |
| | 0 | 587 | | if (Kind != JsonTypeInfoKind.Object) |
| | 0 | 588 | | { |
| | 0 | 589 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 590 | | } |
| | | 591 | | |
| | 0 | 592 | | if (value is not null && !JsonSerializer.IsValidCreationHandlingValue(value.Value)) |
| | 0 | 593 | | { |
| | 0 | 594 | | throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 595 | | } |
| | | 596 | | |
| | 0 | 597 | | _preferredPropertyObjectCreationHandling = value; |
| | 0 | 598 | | } |
| | | 599 | | } |
| | | 600 | | |
| | | 601 | | /// <summary> |
| | | 602 | | /// Gets or sets the <see cref="IJsonTypeInfoResolver"/> from which this metadata instance originated. |
| | | 603 | | /// </summary> |
| | | 604 | | /// <exception cref="InvalidOperationException"> |
| | | 605 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 606 | | /// </exception> |
| | | 607 | | /// <remarks> |
| | | 608 | | /// Metadata used to determine the <see cref="JsonSerializerContext.GeneratedSerializerOptions"/> |
| | | 609 | | /// configuration for the current metadata instance. |
| | | 610 | | /// </remarks> |
| | | 611 | | [EditorBrowsable(EditorBrowsableState.Never)] |
| | | 612 | | public IJsonTypeInfoResolver? OriginatingResolver |
| | | 613 | | { |
| | 0 | 614 | | get => _originatingResolver; |
| | | 615 | | set |
| | 12254 | 616 | | { |
| | 12254 | 617 | | VerifyMutable(); |
| | | 618 | | |
| | 12254 | 619 | | if (value is JsonSerializerContext) |
| | 0 | 620 | | { |
| | | 621 | | // The source generator uses this property setter to brand the metadata instance as user-unmodified. |
| | | 622 | | // Even though users could call the same property setter to unset this flag, this is generally speak |
| | | 623 | | // This flag is only used to determine fast-path invalidation, worst case scenario this would lead t |
| | 0 | 624 | | IsCustomized = false; |
| | 0 | 625 | | } |
| | | 626 | | |
| | 12254 | 627 | | _originatingResolver = value; |
| | 12254 | 628 | | } |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | private IJsonTypeInfoResolver? _originatingResolver; |
| | | 632 | | |
| | | 633 | | /// <summary> |
| | | 634 | | /// Gets or sets an attribute provider corresponding to the deserialization constructor. |
| | | 635 | | /// </summary> |
| | | 636 | | /// <exception cref="InvalidOperationException"> |
| | | 637 | | /// The <see cref="JsonPropertyInfo"/> instance has been locked for further modification. |
| | | 638 | | /// </exception> |
| | | 639 | | /// <remarks> |
| | | 640 | | /// When resolving metadata via the built-in resolvers this will be populated with |
| | | 641 | | /// the underlying <see cref="ConstructorInfo" /> of the serialized property or field. |
| | | 642 | | /// </remarks> |
| | | 643 | | public ICustomAttributeProvider? ConstructorAttributeProvider |
| | | 644 | | { |
| | | 645 | | get |
| | 0 | 646 | | { |
| | 0 | 647 | | Func<ICustomAttributeProvider>? ctorAttrProviderFactory = Volatile.Read(ref ConstructorAttributeProvider |
| | 0 | 648 | | ICustomAttributeProvider? ctorAttrProvider = _constructorAttributeProvider; |
| | | 649 | | |
| | 0 | 650 | | if (ctorAttrProvider is null && ctorAttrProviderFactory is not null) |
| | 0 | 651 | | { |
| | 0 | 652 | | _constructorAttributeProvider = ctorAttrProvider = ctorAttrProviderFactory(); |
| | 0 | 653 | | Volatile.Write(ref ConstructorAttributeProviderFactory, null); |
| | 0 | 654 | | } |
| | | 655 | | |
| | 0 | 656 | | return ctorAttrProvider; |
| | 0 | 657 | | } |
| | | 658 | | internal set |
| | 2851 | 659 | | { |
| | 2851 | 660 | | Debug.Assert(!IsReadOnly); |
| | | 661 | | |
| | 2851 | 662 | | _constructorAttributeProvider = value; |
| | 2851 | 663 | | Volatile.Write(ref ConstructorAttributeProviderFactory, null); |
| | 2851 | 664 | | } |
| | | 665 | | } |
| | | 666 | | |
| | | 667 | | // Metadata emanating from the source generator use delayed attribute provider initialization |
| | | 668 | | // ensuring that reflection metadata resolution remains pay-for-play and is trimmable. |
| | | 669 | | internal Func<ICustomAttributeProvider>? ConstructorAttributeProviderFactory; |
| | | 670 | | private ICustomAttributeProvider? _constructorAttributeProvider; |
| | | 671 | | |
| | | 672 | | internal void VerifyMutable() |
| | 89272 | 673 | | { |
| | 89272 | 674 | | if (IsReadOnly) |
| | 0 | 675 | | { |
| | 0 | 676 | | ThrowHelper.ThrowInvalidOperationException_TypeInfoImmutable(); |
| | | 677 | | } |
| | | 678 | | |
| | 89272 | 679 | | IsCustomized = true; |
| | 89272 | 680 | | } |
| | | 681 | | |
| | | 682 | | /// <summary> |
| | | 683 | | /// Indicates that the current JsonTypeInfo might contain user modifications. |
| | | 684 | | /// Defaults to true, and is only unset by the built-in contract resolvers. |
| | | 685 | | /// </summary> |
| | 126034 | 686 | | internal bool IsCustomized { get; set; } = true; |
| | | 687 | | |
| | 161817 | 688 | | internal bool IsConfigured => _configurationState == ConfigurationState.Configured; |
| | 9810 | 689 | | internal bool IsConfigurationStarted => _configurationState is not ConfigurationState.NotConfigured; |
| | | 690 | | private volatile ConfigurationState _configurationState; |
| | | 691 | | private enum ConfigurationState : byte |
| | | 692 | | { |
| | | 693 | | NotConfigured = 0, |
| | | 694 | | Configuring = 1, |
| | | 695 | | Configured = 2 |
| | | 696 | | }; |
| | | 697 | | |
| | | 698 | | private ExceptionDispatchInfo? _cachedConfigureError; |
| | | 699 | | |
| | | 700 | | internal void EnsureConfigured() |
| | 61791 | 701 | | { |
| | 61791 | 702 | | if (!IsConfigured) |
| | 24508 | 703 | | ConfigureSynchronized(); |
| | | 704 | | |
| | | 705 | | void ConfigureSynchronized() |
| | 24508 | 706 | | { |
| | 24508 | 707 | | Options.MakeReadOnly(); |
| | 24508 | 708 | | MakeReadOnly(); |
| | | 709 | | |
| | 24508 | 710 | | _cachedConfigureError?.Throw(); |
| | | 711 | | |
| | 24508 | 712 | | lock (Options.CacheContext) |
| | 24508 | 713 | | { |
| | 24508 | 714 | | if (_configurationState != ConfigurationState.NotConfigured) |
| | 12254 | 715 | | { |
| | | 716 | | // The value of _configurationState is either |
| | | 717 | | // 'Configuring': recursive instance configured by this thread or |
| | | 718 | | // 'Configured' : instance already configured by another thread. |
| | | 719 | | // We can safely yield the configuration operation in both cases. |
| | 12254 | 720 | | return; |
| | | 721 | | } |
| | | 722 | | |
| | 12254 | 723 | | _cachedConfigureError?.Throw(); |
| | | 724 | | |
| | | 725 | | try |
| | 12254 | 726 | | { |
| | 12254 | 727 | | _configurationState = ConfigurationState.Configuring; |
| | 12254 | 728 | | Configure(); |
| | 12254 | 729 | | _configurationState = ConfigurationState.Configured; |
| | 12254 | 730 | | } |
| | 0 | 731 | | catch (Exception e) |
| | 0 | 732 | | { |
| | 0 | 733 | | _cachedConfigureError = ExceptionDispatchInfo.Capture(e); |
| | 0 | 734 | | _configurationState = ConfigurationState.NotConfigured; |
| | 0 | 735 | | throw; |
| | | 736 | | } |
| | 12254 | 737 | | } |
| | 24508 | 738 | | } |
| | 61791 | 739 | | } |
| | | 740 | | |
| | | 741 | | private void Configure() |
| | 12254 | 742 | | { |
| | 12254 | 743 | | Debug.Assert(Monitor.IsEntered(Options.CacheContext), "Configure called directly, use EnsureConfigured which |
| | 12254 | 744 | | Debug.Assert(Options.IsReadOnly); |
| | 12254 | 745 | | Debug.Assert(IsReadOnly); |
| | | 746 | | |
| | 12254 | 747 | | PropertyInfoForTypeInfo.Configure(); |
| | | 748 | | |
| | 12254 | 749 | | if (PolymorphismOptions != null) |
| | 0 | 750 | | { |
| | | 751 | | // This needs to be done before ConfigureProperties() is called |
| | | 752 | | // JsonPropertyInfo.Configure() must have this value available in order to detect Polymoprhic + cyclic c |
| | 0 | 753 | | PolymorphicTypeResolver = new PolymorphicTypeResolver(Options, PolymorphismOptions, Type, Converter.CanH |
| | 0 | 754 | | } |
| | | 755 | | |
| | 12254 | 756 | | if (Kind == JsonTypeInfoKind.Object) |
| | 1299 | 757 | | { |
| | 1299 | 758 | | ConfigureProperties(); |
| | | 759 | | |
| | 1299 | 760 | | if (DetermineUsesParameterizedConstructor()) |
| | 749 | 761 | | { |
| | 749 | 762 | | ConfigureConstructorParameters(); |
| | 749 | 763 | | } |
| | 1299 | 764 | | } |
| | | 765 | | |
| | 12254 | 766 | | if (ElementType != null) |
| | 1002 | 767 | | { |
| | 1002 | 768 | | _elementTypeInfo ??= Options.GetTypeInfoInternal(ElementType); |
| | 1002 | 769 | | _elementTypeInfo.EnsureConfigured(); |
| | 1002 | 770 | | } |
| | | 771 | | |
| | 12254 | 772 | | if (KeyType != null) |
| | 364 | 773 | | { |
| | 364 | 774 | | _keyTypeInfo ??= Options.GetTypeInfoInternal(KeyType); |
| | 364 | 775 | | _keyTypeInfo.EnsureConfigured(); |
| | 364 | 776 | | } |
| | | 777 | | |
| | 12254 | 778 | | DetermineIsCompatibleWithCurrentOptions(); |
| | 12254 | 779 | | CanUseSerializeHandler = HasSerializeHandler && IsCompatibleWithCurrentOptions; |
| | 12254 | 780 | | } |
| | | 781 | | |
| | | 782 | | /// <summary> |
| | | 783 | | /// Gets any ancestor polymorphic types that declare |
| | | 784 | | /// a type discriminator for the current type. Consulted |
| | | 785 | | /// when serializing polymorphic values as objects. |
| | | 786 | | /// </summary> |
| | | 787 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 788 | | internal JsonTypeInfo? AncestorPolymorphicType |
| | | 789 | | { |
| | | 790 | | get |
| | 0 | 791 | | { |
| | 0 | 792 | | Debug.Assert(IsConfigured); |
| | 0 | 793 | | Debug.Assert(Type != typeof(object)); |
| | | 794 | | |
| | 0 | 795 | | if (!_isAncestorPolymorphicTypeResolved) |
| | 0 | 796 | | { |
| | 0 | 797 | | _ancestorPolymorhicType = PolymorphicTypeResolver.FindNearestPolymorphicBaseType(this); |
| | 0 | 798 | | _isAncestorPolymorphicTypeResolved = true; |
| | 0 | 799 | | } |
| | | 800 | | |
| | 0 | 801 | | return _ancestorPolymorhicType; |
| | 0 | 802 | | } |
| | | 803 | | } |
| | | 804 | | |
| | | 805 | | private JsonTypeInfo? _ancestorPolymorhicType; |
| | | 806 | | private volatile bool _isAncestorPolymorphicTypeResolved; |
| | | 807 | | |
| | | 808 | | /// <summary> |
| | | 809 | | /// Determines if the transitive closure of all JsonTypeInfo metadata referenced |
| | | 810 | | /// by the current type (property types, key types, element types, ...) are |
| | | 811 | | /// compatible with the settings as specified in JsonSerializerOptions. |
| | | 812 | | /// </summary> |
| | | 813 | | private void DetermineIsCompatibleWithCurrentOptions() |
| | 12254 | 814 | | { |
| | | 815 | | // Defines a recursive algorithm validating that the `IsCurrentNodeCompatible` |
| | | 816 | | // predicate is valid for every node in the type graph. This method only checks |
| | | 817 | | // the immediate children, with recursion being driven by the Configure() method. |
| | | 818 | | // Therefore, this method must be called _after_ the child nodes have been configured. |
| | | 819 | | |
| | 12254 | 820 | | Debug.Assert(IsReadOnly); |
| | 12254 | 821 | | Debug.Assert(!IsConfigured); |
| | | 822 | | |
| | 12254 | 823 | | if (!IsCurrentNodeCompatible()) |
| | 0 | 824 | | { |
| | 0 | 825 | | IsCompatibleWithCurrentOptions = false; |
| | 0 | 826 | | return; |
| | | 827 | | } |
| | | 828 | | |
| | 12254 | 829 | | if (_properties != null) |
| | 1299 | 830 | | { |
| | 19485 | 831 | | foreach (JsonPropertyInfo property in _properties) |
| | 7794 | 832 | | { |
| | 7794 | 833 | | Debug.Assert(property.IsConfigured); |
| | | 834 | | |
| | 7794 | 835 | | if (!property.IsPropertyTypeInfoConfigured) |
| | 0 | 836 | | { |
| | | 837 | | // Either an ignored property or property is part of a cycle. |
| | | 838 | | // In both cases we can ignore these instances. |
| | 0 | 839 | | continue; |
| | | 840 | | } |
| | | 841 | | |
| | 7794 | 842 | | if (!property.JsonTypeInfo.IsCompatibleWithCurrentOptions) |
| | 0 | 843 | | { |
| | 0 | 844 | | IsCompatibleWithCurrentOptions = false; |
| | 0 | 845 | | return; |
| | | 846 | | } |
| | 7794 | 847 | | } |
| | 1299 | 848 | | } |
| | | 849 | | |
| | 12254 | 850 | | if (_elementTypeInfo?.IsCompatibleWithCurrentOptions == false || |
| | 12254 | 851 | | _keyTypeInfo?.IsCompatibleWithCurrentOptions == false) |
| | 0 | 852 | | { |
| | 0 | 853 | | IsCompatibleWithCurrentOptions = false; |
| | 0 | 854 | | return; |
| | | 855 | | } |
| | | 856 | | |
| | 12254 | 857 | | Debug.Assert(IsCompatibleWithCurrentOptions); |
| | | 858 | | |
| | | 859 | | // Defines the core predicate that must be checked for every node in the type graph. |
| | | 860 | | bool IsCurrentNodeCompatible() |
| | 12254 | 861 | | { |
| | 12254 | 862 | | if (IsCustomized) |
| | 0 | 863 | | { |
| | | 864 | | // Return false if we have detected contract customization by the user. |
| | 0 | 865 | | return false; |
| | | 866 | | } |
| | | 867 | | |
| | 12254 | 868 | | if (Options.CanUseFastPathSerializationLogic) |
| | 12254 | 869 | | { |
| | | 870 | | // Simple case/backward compatibility: options uses a combination of compatible built-in converters. |
| | 12254 | 871 | | return true; |
| | | 872 | | } |
| | | 873 | | |
| | 0 | 874 | | return OriginatingResolver.IsCompatibleWithOptions(Options); |
| | 12254 | 875 | | } |
| | 12254 | 876 | | } |
| | | 877 | | |
| | | 878 | | /// <summary> |
| | | 879 | | /// Holds the result of the above algorithm -- NB must default to true |
| | | 880 | | /// to establish a base case for recursive types and any JsonIgnored property types. |
| | | 881 | | /// </summary> |
| | 33668 | 882 | | private bool IsCompatibleWithCurrentOptions { get; set; } = true; |
| | | 883 | | |
| | | 884 | | /// <summary> |
| | | 885 | | /// Determine if the current configuration is compatible with using a parameterized constructor. |
| | | 886 | | /// </summary> |
| | | 887 | | internal bool DetermineUsesParameterizedConstructor() |
| | 22096 | 888 | | => Converter.ConstructorIsParameterized && CreateObject is null; |
| | | 889 | | |
| | | 890 | | /// <summary> |
| | | 891 | | /// Creates a blank <see cref="JsonTypeInfo{T}"/> instance. |
| | | 892 | | /// </summary> |
| | | 893 | | /// <typeparam name="T">The type for which contract metadata is specified.</typeparam> |
| | | 894 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> instance the metadata is associated with.</par |
| | | 895 | | /// <returns>A blank <see cref="JsonTypeInfo{T}"/> instance.</returns> |
| | | 896 | | /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception> |
| | | 897 | | /// <remarks> |
| | | 898 | | /// The returned <see cref="JsonTypeInfo{T}"/> will be blank, with the exception of the |
| | | 899 | | /// <see cref="Converter"/> property which will be resolved either from |
| | | 900 | | /// <see cref="JsonSerializerOptions.Converters"/> or the built-in converters for the type. |
| | | 901 | | /// Any converters specified via <see cref="JsonConverterAttribute"/> on the type declaration |
| | | 902 | | /// will not be resolved by this method. |
| | | 903 | | /// |
| | | 904 | | /// What converter does get resolved influences the value of <see cref="Kind"/>, |
| | | 905 | | /// which constrains the type of metadata that can be modified in the <see cref="JsonTypeInfo"/> instance. |
| | | 906 | | /// </remarks> |
| | | 907 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 908 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 909 | | public static JsonTypeInfo<T> CreateJsonTypeInfo<T>(JsonSerializerOptions options) |
| | 0 | 910 | | { |
| | 0 | 911 | | ArgumentNullException.ThrowIfNull(options); |
| | | 912 | | |
| | 0 | 913 | | JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(typeof(T), options, resolveJsonCon |
| | 0 | 914 | | return new JsonTypeInfo<T>(converter, options); |
| | 0 | 915 | | } |
| | | 916 | | |
| | | 917 | | /// <summary> |
| | | 918 | | /// Creates a blank <see cref="JsonTypeInfo"/> instance. |
| | | 919 | | /// </summary> |
| | | 920 | | /// <param name="type">The type for which contract metadata is specified.</param> |
| | | 921 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> instance the metadata is associated with.</par |
| | | 922 | | /// <returns>A blank <see cref="JsonTypeInfo"/> instance.</returns> |
| | | 923 | | /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="options"/> is null.</exce |
| | | 924 | | /// <exception cref="ArgumentException"><paramref name="type"/> cannot be used for serialization.</exception> |
| | | 925 | | /// <remarks> |
| | | 926 | | /// The returned <see cref="JsonTypeInfo"/> will be blank, with the exception of the |
| | | 927 | | /// <see cref="Converter"/> property which will be resolved either from |
| | | 928 | | /// <see cref="JsonSerializerOptions.Converters"/> or the built-in converters for the type. |
| | | 929 | | /// Any converters specified via <see cref="JsonConverterAttribute"/> on the type declaration |
| | | 930 | | /// will not be resolved by this method. |
| | | 931 | | /// |
| | | 932 | | /// What converter does get resolved influences the value of <see cref="Kind"/>, |
| | | 933 | | /// which constrains the type of metadata that can be modified in the <see cref="JsonTypeInfo"/> instance. |
| | | 934 | | /// </remarks> |
| | | 935 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 936 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 937 | | public static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) |
| | 0 | 938 | | { |
| | 0 | 939 | | ArgumentNullException.ThrowIfNull(type); |
| | 0 | 940 | | ArgumentNullException.ThrowIfNull(options); |
| | | 941 | | |
| | 0 | 942 | | if (IsInvalidForSerialization(type)) |
| | 0 | 943 | | { |
| | 0 | 944 | | ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(type), type, null, null); |
| | | 945 | | } |
| | | 946 | | |
| | 0 | 947 | | JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(type, options, resolveJsonConverte |
| | 0 | 948 | | return CreateJsonTypeInfo(type, converter, options); |
| | 0 | 949 | | } |
| | | 950 | | |
| | | 951 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 952 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 953 | | internal static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions option |
| | 12254 | 954 | | { |
| | | 955 | | JsonTypeInfo jsonTypeInfo; |
| | | 956 | | |
| | 12254 | 957 | | if (converter.Type == type) |
| | 12254 | 958 | | { |
| | | 959 | | // For performance, avoid doing a reflection-based instantiation |
| | | 960 | | // if the converter type matches that of the declared type. |
| | 12254 | 961 | | jsonTypeInfo = converter.CreateJsonTypeInfo(options); |
| | 12254 | 962 | | } |
| | | 963 | | else |
| | 0 | 964 | | { |
| | 0 | 965 | | Type jsonTypeInfoType = typeof(JsonTypeInfo<>).MakeGenericType(type); |
| | 0 | 966 | | jsonTypeInfo = (JsonTypeInfo)jsonTypeInfoType.CreateInstanceNoWrapExceptions( |
| | 0 | 967 | | parameterTypes: [typeof(JsonConverter), typeof(JsonSerializerOptions)], |
| | 0 | 968 | | parameters: new object[] { converter, options })!; |
| | 0 | 969 | | } |
| | | 970 | | |
| | 12254 | 971 | | Debug.Assert(jsonTypeInfo.Type == type); |
| | 12254 | 972 | | return jsonTypeInfo; |
| | 12254 | 973 | | } |
| | | 974 | | |
| | | 975 | | /// <summary> |
| | | 976 | | /// Creates a blank <see cref="JsonPropertyInfo"/> instance for the current <see cref="JsonTypeInfo"/>. |
| | | 977 | | /// </summary> |
| | | 978 | | /// <param name="propertyType">The declared type for the property.</param> |
| | | 979 | | /// <param name="name">The property name used in JSON serialization and deserialization.</param> |
| | | 980 | | /// <returns>A blank <see cref="JsonPropertyInfo"/> instance.</returns> |
| | | 981 | | /// <exception cref="ArgumentNullException"><paramref name="propertyType"/> or <paramref name="name"/> is null.< |
| | | 982 | | /// <exception cref="ArgumentException"><paramref name="propertyType"/> cannot be used for serialization.</excep |
| | | 983 | | /// <exception cref="InvalidOperationException">The <see cref="JsonTypeInfo"/> instance has been locked for furt |
| | | 984 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 985 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 986 | | public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name) |
| | 0 | 987 | | { |
| | 0 | 988 | | ArgumentNullException.ThrowIfNull(propertyType); |
| | 0 | 989 | | ArgumentNullException.ThrowIfNull(name); |
| | | 990 | | |
| | 0 | 991 | | if (IsInvalidForSerialization(propertyType)) |
| | 0 | 992 | | { |
| | 0 | 993 | | ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(propertyType), propertyType, Type, |
| | | 994 | | } |
| | | 995 | | |
| | 0 | 996 | | VerifyMutable(); |
| | 0 | 997 | | JsonPropertyInfo propertyInfo = CreatePropertyUsingReflection(propertyType, declaringType: null); |
| | 0 | 998 | | propertyInfo.Name = name; |
| | | 999 | | |
| | 0 | 1000 | | return propertyInfo; |
| | 0 | 1001 | | } |
| | | 1002 | | |
| | | 1003 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 1004 | | [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] |
| | | 1005 | | internal JsonPropertyInfo CreatePropertyUsingReflection(Type propertyType, Type? declaringType) |
| | 7794 | 1006 | | { |
| | | 1007 | | JsonPropertyInfo jsonPropertyInfo; |
| | | 1008 | | |
| | 7794 | 1009 | | if (Options.TryGetTypeInfoCached(propertyType, out JsonTypeInfo? jsonTypeInfo)) |
| | 6437 | 1010 | | { |
| | | 1011 | | // If a JsonTypeInfo has already been cached for the property type, |
| | | 1012 | | // avoid reflection-based initialization by delegating construction |
| | | 1013 | | // of JsonPropertyInfo<T> construction to the property type metadata. |
| | 6437 | 1014 | | jsonPropertyInfo = jsonTypeInfo.CreateJsonPropertyInfo(declaringTypeInfo: this, declaringType, Options); |
| | 6437 | 1015 | | } |
| | | 1016 | | else |
| | 1357 | 1017 | | { |
| | | 1018 | | // Metadata for `propertyType` has not been registered yet. |
| | | 1019 | | // Use reflection to instantiate the correct JsonPropertyInfo<T> |
| | 1357 | 1020 | | Type propertyInfoType = typeof(JsonPropertyInfo<>).MakeGenericType(propertyType); |
| | 1357 | 1021 | | jsonPropertyInfo = (JsonPropertyInfo)propertyInfoType.CreateInstanceNoWrapExceptions( |
| | 1357 | 1022 | | parameterTypes: [typeof(Type), typeof(JsonTypeInfo), typeof(JsonSerializerOptions)], |
| | 1357 | 1023 | | parameters: new object[] { declaringType ?? Type, this, Options })!; |
| | 1357 | 1024 | | } |
| | | 1025 | | |
| | 7794 | 1026 | | Debug.Assert(jsonPropertyInfo.PropertyType == propertyType); |
| | 7794 | 1027 | | return jsonPropertyInfo; |
| | 7794 | 1028 | | } |
| | | 1029 | | |
| | | 1030 | | /// <summary> |
| | | 1031 | | /// Creates a JsonPropertyInfo whose property type matches the type of this JsonTypeInfo instance. |
| | | 1032 | | /// </summary> |
| | | 1033 | | private protected abstract JsonPropertyInfo CreateJsonPropertyInfo(JsonTypeInfo declaringTypeInfo, Type? declari |
| | | 1034 | | |
| | | 1035 | | private protected Dictionary<ParameterLookupKey, JsonParameterInfoValues>? _parameterInfoValuesIndex; |
| | | 1036 | | |
| | | 1037 | | // Untyped, root-level serialization methods |
| | | 1038 | | internal abstract void SerializeAsObject(Utf8JsonWriter writer, object? rootValue); |
| | | 1039 | | internal abstract Task SerializeAsObjectAsync(PipeWriter pipeWriter, object? rootValue, int flushThreshold, Canc |
| | | 1040 | | internal abstract Task SerializeAsObjectAsync(Stream utf8Json, object? rootValue, CancellationToken cancellation |
| | | 1041 | | internal abstract Task SerializeAsObjectAsync(PipeWriter utf8Json, object? rootValue, CancellationToken cancella |
| | | 1042 | | internal abstract void SerializeAsObject(Stream utf8Json, object? rootValue); |
| | | 1043 | | |
| | | 1044 | | // Untyped, root-level deserialization methods |
| | | 1045 | | internal abstract object? DeserializeAsObject(ref Utf8JsonReader reader, ref ReadStack state); |
| | | 1046 | | internal abstract ValueTask<object?> DeserializeAsObjectAsync(PipeReader utf8Json, CancellationToken cancellatio |
| | | 1047 | | internal abstract ValueTask<object?> DeserializeAsObjectAsync(Stream utf8Json, CancellationToken cancellationTok |
| | | 1048 | | internal abstract object? DeserializeAsObject(Stream utf8Json); |
| | | 1049 | | |
| | | 1050 | | internal ref struct PropertyHierarchyResolutionState(JsonSerializerOptions options) |
| | | 1051 | | { |
| | 1299 | 1052 | | public Dictionary<string, (JsonPropertyInfo, int index)> AddedProperties = new(options.PropertyNameCaseInsen |
| | | 1053 | | public Dictionary<string, JsonPropertyInfo>? IgnoredProperties; |
| | | 1054 | | public bool IsPropertyOrderSpecified; |
| | | 1055 | | } |
| | | 1056 | | |
| | | 1057 | | private protected readonly struct ParameterLookupKey(Type type, string name) : IEquatable<ParameterLookupKey> |
| | | 1058 | | { |
| | 22470 | 1059 | | public Type Type { get; } = type; |
| | 35952 | 1060 | | public string Name { get; } = name; |
| | 13482 | 1061 | | public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Name); |
| | 4494 | 1062 | | public bool Equals(ParameterLookupKey other) => Type == other.Type && string.Equals(Name, other.Name, String |
| | 0 | 1063 | | public override bool Equals([NotNullWhen(true)] object? obj) => obj is ParameterLookupKey key && Equals(key) |
| | | 1064 | | } |
| | | 1065 | | |
| | | 1066 | | internal void ConfigureProperties() |
| | 1299 | 1067 | | { |
| | 1299 | 1068 | | Debug.Assert(Kind == JsonTypeInfoKind.Object); |
| | 1299 | 1069 | | Debug.Assert(_propertyCache is null); |
| | 1299 | 1070 | | Debug.Assert(_propertyIndex is null); |
| | 1299 | 1071 | | Debug.Assert(ExtensionDataProperty is null); |
| | | 1072 | | |
| | 1299 | 1073 | | JsonPropertyInfoList properties = PropertyList; |
| | 1299 | 1074 | | StringComparer comparer = Options.PropertyNameCaseInsensitive ? StringComparer.OrdinalIgnoreCase : StringCom |
| | 1299 | 1075 | | Dictionary<string, JsonPropertyInfo> propertyIndex = new(properties.Count, comparer); |
| | 1299 | 1076 | | List<JsonPropertyInfo> propertyCache = new(properties.Count); |
| | | 1077 | | |
| | 1299 | 1078 | | bool arePropertiesSorted = true; |
| | 1299 | 1079 | | int previousPropertyOrder = int.MinValue; |
| | 1299 | 1080 | | BitArray? requiredPropertiesMask = null; |
| | | 1081 | | |
| | 18186 | 1082 | | for (int i = 0; i < properties.Count; i++) |
| | 7794 | 1083 | | { |
| | 7794 | 1084 | | JsonPropertyInfo property = properties[i]; |
| | 7794 | 1085 | | Debug.Assert(property.DeclaringTypeInfo == this); |
| | | 1086 | | |
| | 7794 | 1087 | | if (property.IsExtensionData) |
| | 0 | 1088 | | { |
| | 0 | 1089 | | if (UnmappedMemberHandling is JsonUnmappedMemberHandling.Disallow) |
| | 0 | 1090 | | { |
| | 0 | 1091 | | ThrowHelper.ThrowInvalidOperationException_ExtensionDataConflictsWithUnmappedMemberHandling(Type |
| | | 1092 | | } |
| | | 1093 | | |
| | 0 | 1094 | | if (ExtensionDataProperty != null) |
| | 0 | 1095 | | { |
| | 0 | 1096 | | ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type, typeof(Json |
| | | 1097 | | } |
| | | 1098 | | |
| | 0 | 1099 | | ExtensionDataProperty = property; |
| | 0 | 1100 | | } |
| | | 1101 | | else |
| | 7794 | 1102 | | { |
| | 7794 | 1103 | | property.PropertyIndex = i; |
| | | 1104 | | |
| | 7794 | 1105 | | if (property.IsRequired) |
| | 0 | 1106 | | { |
| | 0 | 1107 | | (requiredPropertiesMask ??= new BitArray(properties.Count))[i] = true; |
| | 0 | 1108 | | } |
| | | 1109 | | |
| | 7794 | 1110 | | if (arePropertiesSorted) |
| | 7794 | 1111 | | { |
| | 7794 | 1112 | | arePropertiesSorted = previousPropertyOrder <= property.Order; |
| | 7794 | 1113 | | previousPropertyOrder = property.Order; |
| | 7794 | 1114 | | } |
| | | 1115 | | |
| | 7794 | 1116 | | if (!propertyIndex.TryAdd(property.Name, property)) |
| | 0 | 1117 | | { |
| | 0 | 1118 | | ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type, property.Name); |
| | | 1119 | | } |
| | | 1120 | | |
| | 7794 | 1121 | | propertyCache.Add(property); |
| | 7794 | 1122 | | } |
| | | 1123 | | |
| | 7794 | 1124 | | property.Configure(); |
| | 7794 | 1125 | | } |
| | | 1126 | | |
| | 1299 | 1127 | | if (!arePropertiesSorted) |
| | 0 | 1128 | | { |
| | | 1129 | | // Properties have been configured by the user and require sorting. |
| | 0 | 1130 | | properties.SortProperties(); |
| | 0 | 1131 | | propertyCache.StableSortByKey(static propInfo => propInfo.Order); |
| | 0 | 1132 | | } |
| | | 1133 | | |
| | 1299 | 1134 | | OptionalPropertiesMask = requiredPropertiesMask?.Not(); |
| | 1299 | 1135 | | _propertyCache = propertyCache.ToArray(); |
| | 1299 | 1136 | | _propertyIndex = propertyIndex; |
| | | 1137 | | |
| | | 1138 | | // Override global UnmappedMemberHandling configuration |
| | | 1139 | | // if type specifies an extension data property. |
| | 1299 | 1140 | | EffectiveUnmappedMemberHandling = UnmappedMemberHandling ?? |
| | 1299 | 1141 | | (ExtensionDataProperty is null |
| | 1299 | 1142 | | ? Options.UnmappedMemberHandling |
| | 1299 | 1143 | | : JsonUnmappedMemberHandling.Skip); |
| | 1299 | 1144 | | } |
| | | 1145 | | |
| | | 1146 | | internal void PopulateParameterInfoValues(JsonParameterInfoValues[] parameterInfoValues) |
| | 749 | 1147 | | { |
| | 749 | 1148 | | if (parameterInfoValues.Length == 0) |
| | 0 | 1149 | | { |
| | 0 | 1150 | | return; |
| | | 1151 | | } |
| | | 1152 | | |
| | 749 | 1153 | | Dictionary<ParameterLookupKey, JsonParameterInfoValues> parameterIndex = new(parameterInfoValues.Length); |
| | 11235 | 1154 | | foreach (JsonParameterInfoValues parameterInfoValue in parameterInfoValues) |
| | 4494 | 1155 | | { |
| | 4494 | 1156 | | ParameterLookupKey paramKey = new(parameterInfoValue.ParameterType, parameterInfoValue.Name); |
| | 4494 | 1157 | | parameterIndex.TryAdd(paramKey, parameterInfoValue); // Ignore conflicts since they are reported at seri |
| | 4494 | 1158 | | } |
| | | 1159 | | |
| | 749 | 1160 | | ParameterCount = parameterInfoValues.Length; |
| | 749 | 1161 | | _parameterInfoValuesIndex = parameterIndex; |
| | 749 | 1162 | | } |
| | | 1163 | | |
| | | 1164 | | internal void ResolveMatchingParameterInfo(JsonPropertyInfo propertyInfo) |
| | 7794 | 1165 | | { |
| | 7794 | 1166 | | Debug.Assert( |
| | 7794 | 1167 | | CreateObjectWithArgs is null || _parameterInfoValuesIndex is not null, |
| | 7794 | 1168 | | "Metadata with parameterized constructors must have populated parameter info metadata."); |
| | | 1169 | | |
| | 7794 | 1170 | | if (_parameterInfoValuesIndex is not { } index) |
| | 3300 | 1171 | | { |
| | 3300 | 1172 | | return; |
| | | 1173 | | } |
| | | 1174 | | |
| | 4494 | 1175 | | string propertyName = propertyInfo.MemberName ?? propertyInfo.Name; |
| | 4494 | 1176 | | ParameterLookupKey propKey = new(propertyInfo.PropertyType, propertyName); |
| | 4494 | 1177 | | if (index.TryGetValue(propKey, out JsonParameterInfoValues? matchingParameterInfoValues)) |
| | 4494 | 1178 | | { |
| | 4494 | 1179 | | propertyInfo.AddJsonParameterInfo(matchingParameterInfoValues); |
| | 4494 | 1180 | | } |
| | 7794 | 1181 | | } |
| | | 1182 | | |
| | | 1183 | | internal void ConfigureConstructorParameters() |
| | 749 | 1184 | | { |
| | 749 | 1185 | | Debug.Assert(Kind == JsonTypeInfoKind.Object); |
| | 749 | 1186 | | Debug.Assert(DetermineUsesParameterizedConstructor()); |
| | 749 | 1187 | | Debug.Assert(_propertyCache is not null); |
| | 749 | 1188 | | Debug.Assert(_parameterCache is null); |
| | | 1189 | | |
| | 749 | 1190 | | List<JsonParameterInfo> parameterCache = new(ParameterCount); |
| | 749 | 1191 | | Dictionary<ParameterLookupKey, JsonParameterInfo> parameterIndex = new(ParameterCount); |
| | | 1192 | | |
| | 11235 | 1193 | | foreach (JsonPropertyInfo propertyInfo in _propertyCache) |
| | 4494 | 1194 | | { |
| | 4494 | 1195 | | JsonParameterInfo? parameterInfo = propertyInfo.AssociatedParameter; |
| | 4494 | 1196 | | if (parameterInfo is null) |
| | 0 | 1197 | | { |
| | 0 | 1198 | | continue; |
| | | 1199 | | } |
| | | 1200 | | |
| | 4494 | 1201 | | string propertyName = propertyInfo.MemberName ?? propertyInfo.Name; |
| | 4494 | 1202 | | ParameterLookupKey paramKey = new(propertyInfo.PropertyType, propertyName); |
| | 4494 | 1203 | | if (!parameterIndex.TryAdd(paramKey, parameterInfo)) |
| | 0 | 1204 | | { |
| | | 1205 | | // Multiple object properties cannot bind to the same constructor parameter. |
| | 0 | 1206 | | ThrowHelper.ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters( |
| | 0 | 1207 | | Type, |
| | 0 | 1208 | | parameterInfo.Name, |
| | 0 | 1209 | | propertyInfo.Name, |
| | 0 | 1210 | | parameterIndex[paramKey].MatchingProperty.Name); |
| | | 1211 | | } |
| | | 1212 | | |
| | 4494 | 1213 | | parameterCache.Add(parameterInfo); |
| | 4494 | 1214 | | } |
| | | 1215 | | |
| | 749 | 1216 | | if (ExtensionDataProperty is { AssociatedParameter: not null }) |
| | 0 | 1217 | | { |
| | 0 | 1218 | | Debug.Assert(ExtensionDataProperty.MemberName != null, "Custom property info cannot be data extension pr |
| | 0 | 1219 | | ThrowHelper.ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(ExtensionDataProperty.Memb |
| | | 1220 | | } |
| | | 1221 | | |
| | 749 | 1222 | | _parameterCache = parameterCache.ToArray(); |
| | 749 | 1223 | | _parameterInfoValuesIndex = null; |
| | 749 | 1224 | | } |
| | | 1225 | | |
| | | 1226 | | internal static void ValidateType(Type type) |
| | 18114 | 1227 | | { |
| | 18114 | 1228 | | if (IsInvalidForSerialization(type)) |
| | 0 | 1229 | | { |
| | 0 | 1230 | | ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(type, declaringType: null, memberI |
| | | 1231 | | } |
| | 18114 | 1232 | | } |
| | | 1233 | | |
| | | 1234 | | internal static bool IsInvalidForSerialization(Type type) |
| | 25908 | 1235 | | { |
| | 25908 | 1236 | | return type == typeof(void) || type.IsPointer || type.IsByRef || IsByRefLike(type) || type.ContainsGenericPa |
| | 25908 | 1237 | | } |
| | | 1238 | | |
| | | 1239 | | internal void PopulatePolymorphismMetadata() |
| | 12254 | 1240 | | { |
| | 12254 | 1241 | | Debug.Assert(!IsReadOnly); |
| | | 1242 | | |
| | 12254 | 1243 | | JsonPolymorphismOptions? options = JsonPolymorphismOptions.CreateFromAttributeDeclarations(Type); |
| | 12254 | 1244 | | if (options != null) |
| | 0 | 1245 | | { |
| | 0 | 1246 | | options.DeclaringTypeInfo = this; |
| | 0 | 1247 | | _polymorphismOptions = options; |
| | 0 | 1248 | | } |
| | 12254 | 1249 | | } |
| | | 1250 | | |
| | | 1251 | | internal void MapInterfaceTypesToCallbacks() |
| | 12254 | 1252 | | { |
| | 12254 | 1253 | | Debug.Assert(!IsReadOnly); |
| | | 1254 | | |
| | 12254 | 1255 | | if (Kind is JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary) |
| | 2301 | 1256 | | { |
| | 2301 | 1257 | | if (typeof(IJsonOnSerializing).IsAssignableFrom(Type)) |
| | 0 | 1258 | | { |
| | 0 | 1259 | | OnSerializing = static obj => ((IJsonOnSerializing)obj).OnSerializing(); |
| | 0 | 1260 | | } |
| | | 1261 | | |
| | 2301 | 1262 | | if (typeof(IJsonOnSerialized).IsAssignableFrom(Type)) |
| | 0 | 1263 | | { |
| | 0 | 1264 | | OnSerialized = static obj => ((IJsonOnSerialized)obj).OnSerialized(); |
| | 0 | 1265 | | } |
| | | 1266 | | |
| | 2301 | 1267 | | if (typeof(IJsonOnDeserializing).IsAssignableFrom(Type)) |
| | 0 | 1268 | | { |
| | 0 | 1269 | | OnDeserializing = static obj => ((IJsonOnDeserializing)obj).OnDeserializing(); |
| | 0 | 1270 | | } |
| | | 1271 | | |
| | 2301 | 1272 | | if (typeof(IJsonOnDeserialized).IsAssignableFrom(Type)) |
| | 0 | 1273 | | { |
| | 0 | 1274 | | OnDeserialized = static obj => ((IJsonOnDeserialized)obj).OnDeserialized(); |
| | 0 | 1275 | | } |
| | 2301 | 1276 | | } |
| | 12254 | 1277 | | } |
| | | 1278 | | |
| | | 1279 | | internal void SetCreateObjectIfCompatible(Delegate? createObject) |
| | 12254 | 1280 | | { |
| | 12254 | 1281 | | Debug.Assert(!IsReadOnly); |
| | | 1282 | | |
| | | 1283 | | // Guard against the reflection resolver/source generator attempting to pass |
| | | 1284 | | // a CreateObject delegate to converters/metadata that do not support it. |
| | 12254 | 1285 | | if (Converter.SupportsCreateObjectDelegate && !Converter.ConstructorIsParameterized) |
| | 1552 | 1286 | | { |
| | 1552 | 1287 | | SetCreateObject(createObject); |
| | 1552 | 1288 | | } |
| | 12254 | 1289 | | } |
| | | 1290 | | |
| | | 1291 | | private static bool IsByRefLike(Type type) |
| | 25908 | 1292 | | { |
| | | 1293 | | #if NET |
| | 25908 | 1294 | | return type.IsByRefLike; |
| | | 1295 | | #else |
| | | 1296 | | if (!type.IsValueType) |
| | | 1297 | | { |
| | | 1298 | | return false; |
| | | 1299 | | } |
| | | 1300 | | |
| | | 1301 | | object[] attributes = type.GetCustomAttributes(inherit: false); |
| | | 1302 | | |
| | | 1303 | | for (int i = 0; i < attributes.Length; i++) |
| | | 1304 | | { |
| | | 1305 | | if (attributes[i].GetType().FullName == "System.Runtime.CompilerServices.IsByRefLikeAttribute") |
| | | 1306 | | { |
| | | 1307 | | return true; |
| | | 1308 | | } |
| | | 1309 | | } |
| | | 1310 | | |
| | | 1311 | | return false; |
| | | 1312 | | #endif |
| | 25908 | 1313 | | } |
| | | 1314 | | |
| | | 1315 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 1316 | | internal bool SupportsPolymorphicDeserialization |
| | | 1317 | | { |
| | | 1318 | | get |
| | 0 | 1319 | | { |
| | 0 | 1320 | | Debug.Assert(IsConfigurationStarted); |
| | 0 | 1321 | | return PolymorphicTypeResolver?.UsesTypeDiscriminators == true; |
| | 0 | 1322 | | } |
| | | 1323 | | } |
| | | 1324 | | |
| | | 1325 | | internal static bool IsValidExtensionDataProperty(Type propertyType) |
| | 0 | 1326 | | { |
| | 0 | 1327 | | return typeof(IDictionary<string, object>).IsAssignableFrom(propertyType) || |
| | 0 | 1328 | | typeof(IDictionary<string, JsonElement>).IsAssignableFrom(propertyType) || |
| | 0 | 1329 | | propertyType == typeof(IReadOnlyDictionary<string, object>) || |
| | 0 | 1330 | | propertyType == typeof(IReadOnlyDictionary<string, JsonElement>) || |
| | 0 | 1331 | | // Avoid a reference to typeof(JsonNode) to support trimming. |
| | 0 | 1332 | | (propertyType.FullName == JsonObjectTypeName && ReferenceEquals(propertyType.Assembly, typeof(JsonTypeIn |
| | 0 | 1333 | | } |
| | | 1334 | | |
| | | 1335 | | private static JsonTypeInfoKind GetTypeInfoKind(Type type, JsonConverter converter) |
| | 12254 | 1336 | | { |
| | 12254 | 1337 | | if (type == typeof(object) && converter.CanBePolymorphic) |
| | 269 | 1338 | | { |
| | | 1339 | | // System.Object is polymorphic and will not respect Properties |
| | 269 | 1340 | | Debug.Assert(converter is ObjectConverter); |
| | 269 | 1341 | | return JsonTypeInfoKind.None; |
| | | 1342 | | } |
| | | 1343 | | |
| | 11985 | 1344 | | switch (converter.ConverterStrategy) |
| | | 1345 | | { |
| | 9684 | 1346 | | case ConverterStrategy.Value: return JsonTypeInfoKind.None; |
| | 1299 | 1347 | | case ConverterStrategy.Object: return JsonTypeInfoKind.Object; |
| | 638 | 1348 | | case ConverterStrategy.Enumerable: return JsonTypeInfoKind.Enumerable; |
| | 364 | 1349 | | case ConverterStrategy.Dictionary: return JsonTypeInfoKind.Dictionary; |
| | | 1350 | | case ConverterStrategy.None: |
| | 0 | 1351 | | Debug.Assert(converter is JsonConverterFactory); |
| | 0 | 1352 | | ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); |
| | | 1353 | | return default; |
| | | 1354 | | default: |
| | 0 | 1355 | | Debug.Fail($"Unexpected class type: {converter.ConverterStrategy}"); |
| | | 1356 | | throw new InvalidOperationException(); |
| | | 1357 | | } |
| | 12254 | 1358 | | } |
| | | 1359 | | |
| | | 1360 | | internal sealed class JsonPropertyInfoList : ConfigurationList<JsonPropertyInfo> |
| | | 1361 | | { |
| | | 1362 | | private readonly JsonTypeInfo _jsonTypeInfo; |
| | | 1363 | | |
| | 1299 | 1364 | | public JsonPropertyInfoList(JsonTypeInfo jsonTypeInfo) |
| | 1299 | 1365 | | { |
| | 1299 | 1366 | | _jsonTypeInfo = jsonTypeInfo; |
| | 1299 | 1367 | | } |
| | | 1368 | | |
| | 0 | 1369 | | public override bool IsReadOnly => _jsonTypeInfo._properties == this && _jsonTypeInfo.IsReadOnly || _jsonTyp |
| | | 1370 | | protected override void OnCollectionModifying() |
| | 7794 | 1371 | | { |
| | 7794 | 1372 | | if (_jsonTypeInfo._properties == this) |
| | 7794 | 1373 | | { |
| | 7794 | 1374 | | _jsonTypeInfo.VerifyMutable(); |
| | 7794 | 1375 | | } |
| | | 1376 | | |
| | 7794 | 1377 | | if (_jsonTypeInfo.Kind != JsonTypeInfoKind.Object) |
| | 0 | 1378 | | { |
| | 0 | 1379 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(_jsonTypeInfo.Kin |
| | | 1380 | | } |
| | 7794 | 1381 | | } |
| | | 1382 | | |
| | | 1383 | | protected override void ValidateAddedValue(JsonPropertyInfo item) |
| | 7794 | 1384 | | { |
| | 7794 | 1385 | | item.EnsureChildOf(_jsonTypeInfo); |
| | 7794 | 1386 | | } |
| | | 1387 | | |
| | | 1388 | | public void SortProperties() |
| | 0 | 1389 | | { |
| | 0 | 1390 | | _list.StableSortByKey(static propInfo => propInfo.Order); |
| | 0 | 1391 | | } |
| | | 1392 | | |
| | | 1393 | | /// <summary> |
| | | 1394 | | /// Used by the built-in resolvers to add property metadata applying conflict resolution. |
| | | 1395 | | /// </summary> |
| | | 1396 | | public void AddPropertyWithConflictResolution(JsonPropertyInfo jsonPropertyInfo, ref PropertyHierarchyResolu |
| | 7794 | 1397 | | { |
| | 7794 | 1398 | | Debug.Assert(!_jsonTypeInfo.IsConfigured); |
| | 7794 | 1399 | | Debug.Assert(jsonPropertyInfo.MemberName != null, "MemberName can be null in custom JsonPropertyInfo ins |
| | | 1400 | | |
| | | 1401 | | // Algorithm should be kept in sync with the Roslyn equivalent in JsonSourceGenerator.Parser.cs |
| | 7794 | 1402 | | string memberName = jsonPropertyInfo.MemberName; |
| | | 1403 | | |
| | 7794 | 1404 | | if (state.AddedProperties.TryAdd(jsonPropertyInfo.Name, (jsonPropertyInfo, Count))) |
| | 7794 | 1405 | | { |
| | 7794 | 1406 | | Add(jsonPropertyInfo); |
| | 7794 | 1407 | | state.IsPropertyOrderSpecified |= jsonPropertyInfo.Order != 0; |
| | 7794 | 1408 | | } |
| | | 1409 | | else |
| | 0 | 1410 | | { |
| | | 1411 | | // The JsonPropertyNameAttribute or naming policy resulted in a collision. |
| | 0 | 1412 | | (JsonPropertyInfo other, int index) = state.AddedProperties[jsonPropertyInfo.Name]; |
| | | 1413 | | |
| | 0 | 1414 | | if (other.IsIgnored) |
| | 0 | 1415 | | { |
| | | 1416 | | // Overwrite previously cached property since it has [JsonIgnore]. |
| | 0 | 1417 | | state.AddedProperties[jsonPropertyInfo.Name] = (jsonPropertyInfo, index); |
| | 0 | 1418 | | this[index] = jsonPropertyInfo; |
| | 0 | 1419 | | state.IsPropertyOrderSpecified |= jsonPropertyInfo.Order != 0; |
| | 0 | 1420 | | } |
| | | 1421 | | else |
| | 0 | 1422 | | { |
| | 0 | 1423 | | bool ignoreCurrentProperty = |
| | 0 | 1424 | | // Does the current property have `JsonIgnoreAttribute`? |
| | 0 | 1425 | | jsonPropertyInfo.IsIgnored || |
| | 0 | 1426 | | // Is the current property hidden by the previously cached property |
| | 0 | 1427 | | // (with `new` keyword, or by overriding)? |
| | 0 | 1428 | | jsonPropertyInfo.IsOverriddenOrShadowedBy(other) || |
| | 0 | 1429 | | // Was a property with the same CLR name ignored? That property hid the current property, |
| | 0 | 1430 | | // thus, if it was ignored, the current property should be ignored too. |
| | 0 | 1431 | | (state.IgnoredProperties?.TryGetValue(memberName, out JsonPropertyInfo? ignored) == true && |
| | | 1432 | | |
| | 0 | 1433 | | if (!ignoreCurrentProperty) |
| | 0 | 1434 | | { |
| | 0 | 1435 | | ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(_jsonTypeInfo.Type |
| | | 1436 | | } |
| | 0 | 1437 | | } |
| | 0 | 1438 | | } |
| | | 1439 | | |
| | 7794 | 1440 | | if (jsonPropertyInfo.IsIgnored) |
| | 0 | 1441 | | { |
| | 0 | 1442 | | (state.IgnoredProperties ??= new())[memberName] = jsonPropertyInfo; |
| | 0 | 1443 | | } |
| | 7794 | 1444 | | } |
| | | 1445 | | } |
| | | 1446 | | |
| | | 1447 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | 0 | 1448 | | private string DebuggerDisplay => $"Type = {Type.Name}, Kind = {Kind}"; |
| | | 1449 | | } |
| | | 1450 | | } |