| | | 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> |
| | 0 | 36 | | internal BitArray? OptionalPropertiesMask { get; private set; } |
| | 0 | 37 | | internal bool ShouldTrackRequiredProperties => OptionalPropertiesMask is not null; |
| | | 38 | | |
| | 0 | 39 | | internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options) |
| | 0 | 40 | | { |
| | 0 | 41 | | Type = type; |
| | 0 | 42 | | Options = options; |
| | 0 | 43 | | Converter = converter; |
| | 0 | 44 | | Kind = GetTypeInfoKind(type, converter); |
| | 0 | 45 | | PropertyInfoForTypeInfo = CreatePropertyInfoForTypeInfo(); |
| | 0 | 46 | | ElementType = converter.ElementType; |
| | 0 | 47 | | KeyType = converter.KeyType; |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Gets the element type corresponding to an enumerable, dictionary or optional type. |
| | | 52 | | /// </summary> |
| | | 53 | | /// <remarks> |
| | | 54 | | /// Returns the element type for enumerable types, the value type for dictionary types, |
| | | 55 | | /// and the underlying type for <see cref="Nullable{T}"/> or F# optional types. |
| | | 56 | | /// |
| | | 57 | | /// Returns <see langword="null"/> for all other types or types using custom converters. |
| | | 58 | | /// </remarks> |
| | 0 | 59 | | public Type? ElementType { get; } |
| | | 60 | | |
| | | 61 | | /// <summary> |
| | | 62 | | /// Gets the key type corresponding to a dictionary type. |
| | | 63 | | /// </summary> |
| | | 64 | | /// <remarks> |
| | | 65 | | /// Returns the key type for dictionary types. |
| | | 66 | | /// |
| | | 67 | | /// Returns <see langword="null"/> for all other types or types using custom converters. |
| | | 68 | | /// </remarks> |
| | 0 | 69 | | public Type? KeyType { get; } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Gets or sets a parameterless factory to be used on deserialization. |
| | | 73 | | /// </summary> |
| | | 74 | | /// <exception cref="InvalidOperationException"> |
| | | 75 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 76 | | /// |
| | | 77 | | /// -or- |
| | | 78 | | /// |
| | | 79 | | /// A parameterless factory is not supported for the current metadata <see cref="Kind"/>. |
| | | 80 | | /// </exception> |
| | | 81 | | /// <remarks> |
| | | 82 | | /// If set to <see langword="null" />, any attempt to deserialize instances of the given type will result in an |
| | | 83 | | /// |
| | | 84 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 85 | | /// types with a single default constructor or default constructors annotated with <see cref="JsonConstructorAtt |
| | | 86 | | /// will be mapped to this delegate. |
| | | 87 | | /// </remarks> |
| | | 88 | | public Func<object>? CreateObject |
| | | 89 | | { |
| | 0 | 90 | | get => _createObject; |
| | | 91 | | set |
| | 0 | 92 | | { |
| | 0 | 93 | | SetCreateObject(value); |
| | 0 | 94 | | } |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | private protected abstract void SetCreateObject(Delegate? createObject); |
| | | 98 | | private protected Func<object>? _createObject; |
| | | 99 | | |
| | 0 | 100 | | internal Func<object>? CreateObjectForExtensionDataProperty { get; set; } |
| | | 101 | | |
| | | 102 | | /// <summary> |
| | | 103 | | /// Gets or sets a callback to be invoked before serialization occurs. |
| | | 104 | | /// </summary> |
| | | 105 | | /// <exception cref="InvalidOperationException"> |
| | | 106 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 107 | | /// |
| | | 108 | | /// -or- |
| | | 109 | | /// |
| | | 110 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 111 | | /// </exception> |
| | | 112 | | /// <remarks> |
| | | 113 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 114 | | /// the value of this callback will be mapped from any <see cref="IJsonOnSerializing"/> implementation on the ty |
| | | 115 | | /// </remarks> |
| | | 116 | | public Action<object>? OnSerializing |
| | | 117 | | { |
| | 0 | 118 | | get; |
| | | 119 | | set |
| | 0 | 120 | | { |
| | 0 | 121 | | VerifyMutable(); |
| | | 122 | | |
| | 0 | 123 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 124 | | { |
| | 0 | 125 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 126 | | } |
| | | 127 | | |
| | 0 | 128 | | field = value; |
| | 0 | 129 | | } |
| | | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Gets or sets a callback to be invoked after serialization occurs. |
| | | 134 | | /// </summary> |
| | | 135 | | /// <exception cref="InvalidOperationException"> |
| | | 136 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 137 | | /// |
| | | 138 | | /// -or- |
| | | 139 | | /// |
| | | 140 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 141 | | /// </exception> |
| | | 142 | | /// <remarks> |
| | | 143 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 144 | | /// the value of this callback will be mapped from any <see cref="IJsonOnSerialized"/> implementation on the typ |
| | | 145 | | /// </remarks> |
| | | 146 | | public Action<object>? OnSerialized |
| | | 147 | | { |
| | 0 | 148 | | get; |
| | | 149 | | set |
| | 0 | 150 | | { |
| | 0 | 151 | | VerifyMutable(); |
| | | 152 | | |
| | 0 | 153 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 154 | | { |
| | 0 | 155 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 156 | | } |
| | | 157 | | |
| | 0 | 158 | | field = value; |
| | 0 | 159 | | } |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | /// <summary> |
| | | 163 | | /// Gets or sets a callback to be invoked before deserialization occurs. |
| | | 164 | | /// </summary> |
| | | 165 | | /// <exception cref="InvalidOperationException"> |
| | | 166 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 167 | | /// |
| | | 168 | | /// -or- |
| | | 169 | | /// |
| | | 170 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 171 | | /// </exception> |
| | | 172 | | /// <remarks> |
| | | 173 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 174 | | /// the value of this callback will be mapped from any <see cref="IJsonOnDeserializing"/> implementation on the |
| | | 175 | | /// </remarks> |
| | | 176 | | public Action<object>? OnDeserializing |
| | | 177 | | { |
| | 0 | 178 | | get; |
| | | 179 | | set |
| | 0 | 180 | | { |
| | 0 | 181 | | VerifyMutable(); |
| | | 182 | | |
| | 0 | 183 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 184 | | { |
| | 0 | 185 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 186 | | } |
| | | 187 | | |
| | 0 | 188 | | if (Converter.IsConvertibleCollection) |
| | 0 | 189 | | { |
| | | 190 | | // The values for convertible collections aren't available at the start of deserialization. |
| | 0 | 191 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOnDeserializingCallbacksNotSupported(Type); |
| | | 192 | | } |
| | | 193 | | |
| | 0 | 194 | | field = value; |
| | 0 | 195 | | } |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | /// <summary> |
| | | 199 | | /// Gets or sets a callback to be invoked after deserialization occurs. |
| | | 200 | | /// </summary> |
| | | 201 | | /// <exception cref="InvalidOperationException"> |
| | | 202 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 203 | | /// |
| | | 204 | | /// -or- |
| | | 205 | | /// |
| | | 206 | | /// Serialization callbacks are only supported for <see cref="JsonTypeInfoKind.Object"/> metadata. |
| | | 207 | | /// </exception> |
| | | 208 | | /// <remarks> |
| | | 209 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 210 | | /// the value of this callback will be mapped from any <see cref="IJsonOnDeserialized"/> implementation on the t |
| | | 211 | | /// </remarks> |
| | | 212 | | public Action<object>? OnDeserialized |
| | | 213 | | { |
| | 0 | 214 | | get; |
| | | 215 | | set |
| | 0 | 216 | | { |
| | 0 | 217 | | VerifyMutable(); |
| | | 218 | | |
| | 0 | 219 | | if (Kind is not (JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary)) |
| | 0 | 220 | | { |
| | 0 | 221 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 222 | | } |
| | | 223 | | |
| | 0 | 224 | | field = value; |
| | 0 | 225 | | } |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | /// <summary> |
| | | 229 | | /// Gets the list of <see cref="JsonPropertyInfo"/> metadata corresponding to the current type. |
| | | 230 | | /// </summary> |
| | | 231 | | /// <remarks> |
| | | 232 | | /// Property is only applicable to metadata of kind <see cref="JsonTypeInfoKind.Object"/>. |
| | | 233 | | /// For other kinds an empty, read-only list will be returned. |
| | | 234 | | /// |
| | | 235 | | /// The order of <see cref="JsonPropertyInfo"/> entries in the list determines the serialization order, |
| | | 236 | | /// unless either of the entries specifies a non-zero <see cref="JsonPropertyInfo.Order"/> value, |
| | | 237 | | /// in which case the properties will be stable sorted by <see cref="JsonPropertyInfo.Order"/>. |
| | | 238 | | /// |
| | | 239 | | /// It is required that added <see cref="JsonPropertyInfo"/> entries are unique up to <see cref="JsonPropertyInf |
| | | 240 | | /// however this will only be validated on serialization, once the metadata instance gets locked for further mod |
| | | 241 | | /// </remarks> |
| | 0 | 242 | | public IList<JsonPropertyInfo> Properties => PropertyList; |
| | | 243 | | |
| | | 244 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 245 | | internal JsonPropertyInfoList PropertyList |
| | | 246 | | { |
| | | 247 | | get |
| | 0 | 248 | | { |
| | 0 | 249 | | return _properties ?? CreatePropertyList(); |
| | | 250 | | JsonPropertyInfoList CreatePropertyList() |
| | 0 | 251 | | { |
| | 0 | 252 | | var list = new JsonPropertyInfoList(this); |
| | 0 | 253 | | if (_sourceGenDelayedPropertyInitializer is { } propInit) |
| | 0 | 254 | | { |
| | | 255 | | // .NET 6 source gen backward compatibility -- ensure that the |
| | | 256 | | // property initializer delegate is invoked lazily. |
| | 0 | 257 | | JsonMetadataServices.PopulateProperties(this, list, propInit); |
| | 0 | 258 | | } |
| | | 259 | | |
| | 0 | 260 | | JsonPropertyInfoList? result = Interlocked.CompareExchange(ref _properties, list, null); |
| | 0 | 261 | | _sourceGenDelayedPropertyInitializer = null; |
| | 0 | 262 | | return result ?? list; |
| | 0 | 263 | | } |
| | 0 | 264 | | } |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | /// <summary> |
| | | 268 | | /// Stores the .NET 6-style property initialization delegate for delayed evaluation. |
| | | 269 | | /// </summary> |
| | | 270 | | internal Func<JsonSerializerContext, JsonPropertyInfo[]>? SourceGenDelayedPropertyInitializer |
| | | 271 | | { |
| | | 272 | | get => _sourceGenDelayedPropertyInitializer; |
| | | 273 | | set |
| | 0 | 274 | | { |
| | 0 | 275 | | Debug.Assert(!IsReadOnly); |
| | 0 | 276 | | Debug.Assert(_properties is null, "must not be set if a property list has been initialized."); |
| | 0 | 277 | | _sourceGenDelayedPropertyInitializer = value; |
| | 0 | 278 | | } |
| | | 279 | | } |
| | | 280 | | |
| | | 281 | | private Func<JsonSerializerContext, JsonPropertyInfo[]>? _sourceGenDelayedPropertyInitializer; |
| | | 282 | | private JsonPropertyInfoList? _properties; |
| | | 283 | | |
| | | 284 | | /// <summary> |
| | | 285 | | /// Gets or sets a configuration object specifying polymorphism metadata. |
| | | 286 | | /// </summary> |
| | | 287 | | /// <exception cref="ArgumentException"> |
| | | 288 | | /// <paramref name="value" /> has been associated with a different <see cref="JsonTypeInfo"/> instance. |
| | | 289 | | /// </exception> |
| | | 290 | | /// <exception cref="InvalidOperationException"> |
| | | 291 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 292 | | /// |
| | | 293 | | /// -or- |
| | | 294 | | /// |
| | | 295 | | /// Polymorphic serialization is not supported for the current metadata <see cref="Kind"/>. |
| | | 296 | | /// </exception> |
| | | 297 | | /// <remarks> |
| | | 298 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 299 | | /// the configuration of this setting will be mapped from any <see cref="JsonDerivedTypeAttribute"/> or <see cre |
| | | 300 | | /// </remarks> |
| | | 301 | | public JsonPolymorphismOptions? PolymorphismOptions |
| | | 302 | | { |
| | 0 | 303 | | get => _polymorphismOptions; |
| | | 304 | | set |
| | 0 | 305 | | { |
| | 0 | 306 | | VerifyMutable(); |
| | | 307 | | |
| | 0 | 308 | | if (value is not null) |
| | 0 | 309 | | { |
| | 0 | 310 | | if (Kind == JsonTypeInfoKind.None) |
| | 0 | 311 | | { |
| | 0 | 312 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 313 | | } |
| | | 314 | | |
| | 0 | 315 | | if (value.DeclaringTypeInfo is not null && value.DeclaringTypeInfo != this) |
| | 0 | 316 | | { |
| | 0 | 317 | | ThrowHelper.ThrowArgumentException_JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo(na |
| | | 318 | | } |
| | | 319 | | |
| | 0 | 320 | | value.DeclaringTypeInfo = this; |
| | 0 | 321 | | } |
| | | 322 | | |
| | 0 | 323 | | _polymorphismOptions = value; |
| | 0 | 324 | | } |
| | | 325 | | } |
| | | 326 | | |
| | | 327 | | internal void SetPolymorphismOptions(JsonPolymorphismOptions options) |
| | 0 | 328 | | { |
| | 0 | 329 | | Debug.Assert(!IsReadOnly); |
| | 0 | 330 | | Debug.Assert(options.DeclaringTypeInfo is null || options.DeclaringTypeInfo == this); |
| | | 331 | | |
| | 0 | 332 | | options.DeclaringTypeInfo = this; |
| | 0 | 333 | | _polymorphismOptions = options; |
| | 0 | 334 | | } |
| | | 335 | | |
| | | 336 | | /// <summary> |
| | | 337 | | /// Specifies whether the current instance has been locked for modification. |
| | | 338 | | /// </summary> |
| | | 339 | | /// <remarks> |
| | | 340 | | /// A <see cref="JsonTypeInfo"/> instance can be locked either if |
| | | 341 | | /// it has been passed to one of the <see cref="JsonSerializer"/> methods, |
| | | 342 | | /// has been associated with a <see cref="JsonSerializerContext"/> instance, |
| | | 343 | | /// or a user explicitly called the <see cref="MakeReadOnly"/> method on the instance. |
| | | 344 | | /// </remarks> |
| | 0 | 345 | | public bool IsReadOnly { get; private set; } |
| | | 346 | | |
| | | 347 | | /// <summary> |
| | | 348 | | /// Locks the current instance for further modification. |
| | | 349 | | /// </summary> |
| | | 350 | | /// <remarks>This method is idempotent.</remarks> |
| | 0 | 351 | | public void MakeReadOnly() => IsReadOnly = true; |
| | | 352 | | |
| | | 353 | | private protected JsonPolymorphismOptions? _polymorphismOptions; |
| | | 354 | | |
| | | 355 | | /// <summary> |
| | | 356 | | /// Gets the list of union case type metadata for this type. |
| | | 357 | | /// </summary> |
| | | 358 | | /// <remarks> |
| | | 359 | | /// <para> |
| | | 360 | | /// This property is only meaningful when <see cref="Kind"/> is <see cref="JsonTypeInfoKind.Union"/>. |
| | | 361 | | /// The list is mutable during configuration and frozen at finalization time. |
| | | 362 | | /// </para> |
| | | 363 | | /// <para> |
| | | 364 | | /// For types recognized as unions via <c>System.Runtime.CompilerServices.UnionAttribute</c>, |
| | | 365 | | /// the list is automatically populated. For contract customization, users can |
| | | 366 | | /// populate this list manually. |
| | | 367 | | /// </para> |
| | | 368 | | /// </remarks> |
| | 0 | 369 | | public IList<JsonUnionCaseInfo> UnionCases => UnionCaseList; |
| | | 370 | | |
| | | 371 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 372 | | internal JsonUnionCaseInfoList UnionCaseList |
| | | 373 | | { |
| | | 374 | | get |
| | 0 | 375 | | { |
| | 0 | 376 | | return _unionCases ?? CreateUnionCaseList(); |
| | | 377 | | JsonUnionCaseInfoList CreateUnionCaseList() |
| | 0 | 378 | | { |
| | 0 | 379 | | var list = new JsonUnionCaseInfoList(this); |
| | 0 | 380 | | JsonUnionCaseInfoList? result = Interlocked.CompareExchange(ref _unionCases, list, null); |
| | 0 | 381 | | return result ?? list; |
| | 0 | 382 | | } |
| | 0 | 383 | | } |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | private JsonUnionCaseInfoList? _unionCases; |
| | | 387 | | |
| | | 388 | | internal sealed class JsonUnionCaseInfoList : ConfigurationList<JsonUnionCaseInfo> |
| | | 389 | | { |
| | | 390 | | private readonly JsonTypeInfo _parent; |
| | | 391 | | |
| | 0 | 392 | | public JsonUnionCaseInfoList(JsonTypeInfo parent, IEnumerable<JsonUnionCaseInfo>? source = null) : base(sour |
| | 0 | 393 | | { |
| | 0 | 394 | | _parent = parent; |
| | 0 | 395 | | } |
| | | 396 | | |
| | 0 | 397 | | public override bool IsReadOnly => _parent.IsReadOnly; |
| | 0 | 398 | | protected override void OnCollectionModifying() => _parent.VerifyMutable(); |
| | | 399 | | } |
| | | 400 | | |
| | | 401 | | /// <summary> |
| | | 402 | | /// Gets or sets the delegate that classifies JSON payloads to determine the target type |
| | | 403 | | /// during deserialization. |
| | | 404 | | /// </summary> |
| | | 405 | | /// <remarks> |
| | | 406 | | /// <para> |
| | | 407 | | /// This is the shared classification property for both polymorphic types and union types. |
| | | 408 | | /// </para> |
| | | 409 | | /// <para> |
| | | 410 | | /// For <strong>polymorphic types</strong>: when set, bypasses the standard discriminator-based |
| | | 411 | | /// type resolution (scanning for a <c>$type</c> property). When <see langword="null"/> |
| | | 412 | | /// (default), the existing discriminator-based approach is used unchanged. |
| | | 413 | | /// </para> |
| | | 414 | | /// <para> |
| | | 415 | | /// For <strong>union types</strong>: determines which case type matches the JSON payload. |
| | | 416 | | /// When set by the user, replaces the default token-based matching. |
| | | 417 | | /// </para> |
| | | 418 | | /// </remarks> |
| | | 419 | | public JsonTypeClassifier? TypeClassifier |
| | | 420 | | { |
| | | 421 | | get |
| | 0 | 422 | | { |
| | 0 | 423 | | if (_typeClassifierResolutionPending) |
| | 0 | 424 | | { |
| | 0 | 425 | | ConfigureTypeClassifier(); |
| | 0 | 426 | | } |
| | | 427 | | |
| | 0 | 428 | | return _typeClassifier; |
| | 0 | 429 | | } |
| | | 430 | | set |
| | 0 | 431 | | { |
| | 0 | 432 | | VerifyMutable(); |
| | | 433 | | // Explicit user assignment wins; discard any pending factory. |
| | 0 | 434 | | _typeClassifier = value; |
| | 0 | 435 | | _typeClassifierFactory = null; |
| | 0 | 436 | | _typeClassifierResolutionPending = false; |
| | 0 | 437 | | } |
| | | 438 | | } |
| | | 439 | | |
| | | 440 | | private JsonTypeClassifier? _typeClassifier; |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Gets or sets the weakly-typed delegate that deconstructs a union instance into |
| | | 444 | | /// its case type and case value. |
| | | 445 | | /// </summary> |
| | | 446 | | /// <remarks> |
| | | 447 | | /// <para> |
| | | 448 | | /// The delegate combines object classification and value extraction in a single call, |
| | | 449 | | /// returning a tuple of <c>(Type? CaseType, object? CaseValue)</c>. |
| | | 450 | | /// </para> |
| | | 451 | | /// <para> |
| | | 452 | | /// <c>CaseType</c> doubles as the discriminator for the union's null state: |
| | | 453 | | /// </para> |
| | | 454 | | /// <list type="bullet"> |
| | | 455 | | /// <item> |
| | | 456 | | /// <description> |
| | | 457 | | /// A non-<see langword="null"/> <c>CaseType</c> instructs the converter to serialize |
| | | 458 | | /// <c>CaseValue</c> using the <see cref="JsonTypeInfo"/> registered for that case |
| | | 459 | | /// type. <c>CaseValue</c> may be <see langword="null"/>, in which case the JSON |
| | | 460 | | /// output is <c>null</c> rendered through that case type's contract (this preserves |
| | | 461 | | /// per-case null annotations). The <c>CaseType</c> must be one of the union's |
| | | 462 | | /// declared case types; returning a runtime type that is more derived than any |
| | | 463 | | /// declared case violates STJ contract invariants. |
| | | 464 | | /// </description> |
| | | 465 | | /// </item> |
| | | 466 | | /// <item> |
| | | 467 | | /// <description> |
| | | 468 | | /// A <see langword="null"/> <c>CaseType</c> signals that the instance is the |
| | | 469 | | /// canonical null union value. The converter writes JSON <c>null</c> directly, |
| | | 470 | | /// bypassing all per-case contracts; <c>CaseValue</c> is ignored. |
| | | 471 | | /// </description> |
| | | 472 | | /// </item> |
| | | 473 | | /// </list> |
| | | 474 | | /// <para> |
| | | 475 | | /// Prefer setting the strongly-typed <see cref="JsonTypeInfo{T}.UnionDeconstructor"/> |
| | | 476 | | /// on <see cref="JsonTypeInfo{T}"/> to avoid boxing when the union type is a value type. |
| | | 477 | | /// </para> |
| | | 478 | | /// </remarks> |
| | | 479 | | public Func<object, (Type? CaseType, object? CaseValue)>? UnionDeconstructor |
| | | 480 | | { |
| | 0 | 481 | | get => _unionDeconstructor; |
| | | 482 | | set |
| | 0 | 483 | | { |
| | 0 | 484 | | VerifyMutable(); |
| | 0 | 485 | | SetUnionDeconstructor(value); |
| | 0 | 486 | | } |
| | | 487 | | } |
| | | 488 | | |
| | | 489 | | private protected virtual void SetUnionDeconstructor(Delegate? deconstructor) |
| | 0 | 490 | | { |
| | 0 | 491 | | Debug.Assert(deconstructor is null or Func<object, (Type?, object?)>); |
| | 0 | 492 | | _unionDeconstructor = (Func<object, (Type?, object?)>?)deconstructor; |
| | 0 | 493 | | } |
| | | 494 | | |
| | | 495 | | private protected Func<object, (Type?, object?)>? _unionDeconstructor; |
| | | 496 | | |
| | | 497 | | /// <summary> |
| | | 498 | | /// Gets or sets the weakly-typed delegate that constructs a union instance from |
| | | 499 | | /// a case type and case value. |
| | | 500 | | /// </summary> |
| | | 501 | | /// <remarks> |
| | | 502 | | /// <para> |
| | | 503 | | /// The delegate takes a <see cref="Type"/> parameter naming the resolved case type |
| | | 504 | | /// (as produced by classification) and an <c>object?</c> case value, returning the |
| | | 505 | | /// constructed union instance. The <c>caseType</c> parameter is always non-<see langword="null"/> |
| | | 506 | | /// and disambiguates among overlapping case types (e.g., <c>Labrador : Dog</c>). |
| | | 507 | | /// </para> |
| | | 508 | | /// <para> |
| | | 509 | | /// The delegate also encapsulates the union's null-handling policy. When the |
| | | 510 | | /// converter encounters a JSON <see cref="JsonTokenType.Null"/> token, it bypasses |
| | | 511 | | /// any configured <see cref="TypeClassifier"/> and invokes the delegate with a |
| | | 512 | | /// <see langword="null"/> case value. Implementations should produce the canonical |
| | | 513 | | /// null-holding union instance when at least one case is nullable, and otherwise |
| | | 514 | | /// throw a <see cref="JsonException"/>. On the null path the <c>caseType</c> argument |
| | | 515 | | /// is set to one of the declared nullable case types but its specific value should |
| | | 516 | | /// be ignored; per union semantics, all nullable cases collapse to the same null |
| | | 517 | | /// instance. |
| | | 518 | | /// </para> |
| | | 519 | | /// <para> |
| | | 520 | | /// Prefer setting the strongly-typed <see cref="JsonTypeInfo{T}.UnionConstructor"/> |
| | | 521 | | /// on <see cref="JsonTypeInfo{T}"/> to avoid boxing when the union type is a value type. |
| | | 522 | | /// </para> |
| | | 523 | | /// </remarks> |
| | | 524 | | public Func<Type, object?, object>? UnionConstructor |
| | | 525 | | { |
| | 0 | 526 | | get => _unionConstructor; |
| | | 527 | | set |
| | 0 | 528 | | { |
| | 0 | 529 | | VerifyMutable(); |
| | 0 | 530 | | SetUnionConstructor(value); |
| | 0 | 531 | | } |
| | | 532 | | } |
| | | 533 | | |
| | | 534 | | private protected virtual void SetUnionConstructor(Delegate? constructor) |
| | 0 | 535 | | { |
| | 0 | 536 | | Debug.Assert(constructor is null or Func<Type, object?, object>); |
| | 0 | 537 | | _unionConstructor = (Func<Type, object?, object>?)constructor; |
| | 0 | 538 | | } |
| | | 539 | | |
| | | 540 | | private protected Func<Type, object?, object>? _unionConstructor; |
| | | 541 | | |
| | | 542 | | /// <summary> |
| | | 543 | | /// Pre-built JSON value shape to type map for default union deserialization (no custom classifier). |
| | | 544 | | /// Maps each <see cref="JsonValueType"/> to the first-declared case type that |
| | | 545 | | /// serializes as that value shape. Populated at configuration time from <see cref="UnionCases"/>. |
| | | 546 | | /// </summary> |
| | 0 | 547 | | internal Dictionary<JsonValueType, Type>? UnionValueTypeMap { get; set; } |
| | | 548 | | |
| | | 549 | | /// <summary> |
| | | 550 | | /// Bitmask of <see cref="JsonValueType"/> shapes that two or more declared case types both |
| | | 551 | | /// serialize as. Populated alongside <see cref="UnionValueTypeMap"/>; used at deserialize |
| | | 552 | | /// time to surface a precise "ambiguous case" error when one of these value shapes appears. |
| | | 553 | | /// <see cref="JsonValueType.None"/> means no ambiguous shapes were detected. |
| | | 554 | | /// </summary> |
| | 0 | 555 | | internal JsonValueType UnionAmbiguousValueTypes { get; set; } |
| | | 556 | | |
| | | 557 | | /// <summary> |
| | | 558 | | /// First nullable union case type, if any. Populated at configuration time from <see cref="UnionCases"/>. |
| | | 559 | | /// </summary> |
| | 0 | 560 | | internal Type? UnionNullableCaseType { get; set; } |
| | | 561 | | |
| | | 562 | | /// <summary> |
| | | 563 | | /// Optional per-type factory captured during metadata creation (resolver phase) |
| | | 564 | | /// from <see cref="JsonUnionAttribute.TypeClassifier"/> or <see cref="JsonPolymorphicAttribute.TypeClassifier"/ |
| | | 565 | | /// </summary> |
| | | 566 | | internal JsonTypeClassifierFactory? TypeClassifierFactory |
| | | 567 | | { |
| | 0 | 568 | | get => _typeClassifierFactory; |
| | | 569 | | set |
| | 0 | 570 | | { |
| | 0 | 571 | | Debug.Assert(!IsReadOnly); |
| | 0 | 572 | | _typeClassifierFactory = value; |
| | 0 | 573 | | } |
| | | 574 | | } |
| | | 575 | | |
| | | 576 | | /// <summary> |
| | | 577 | | /// Indicates whether type classifier resolution should run lazily from the |
| | | 578 | | /// <see cref="TypeClassifier"/> getter or during metadata configuration. |
| | | 579 | | /// </summary> |
| | | 580 | | internal bool TypeClassifierResolutionPending |
| | | 581 | | { |
| | | 582 | | get => _typeClassifierResolutionPending; |
| | | 583 | | set |
| | 0 | 584 | | { |
| | 0 | 585 | | Debug.Assert(!IsReadOnly); |
| | 0 | 586 | | _typeClassifierResolutionPending = value; |
| | 0 | 587 | | } |
| | | 588 | | } |
| | | 589 | | |
| | | 590 | | private JsonTypeClassifierFactory? _typeClassifierFactory; |
| | | 591 | | private volatile bool _typeClassifierResolutionPending; |
| | | 592 | | |
| | 0 | 593 | | internal object? CreateObjectWithArgs { get; set; } |
| | | 594 | | |
| | | 595 | | // Add method delegate for non-generic Stack and Queue; and types that derive from them. |
| | 0 | 596 | | internal object? AddMethodDelegate { get; set; } |
| | | 597 | | |
| | 0 | 598 | | internal JsonPropertyInfo? ExtensionDataProperty { get; private set; } |
| | | 599 | | |
| | 0 | 600 | | internal PolymorphicTypeResolver? PolymorphicTypeResolver { get; private set; } |
| | | 601 | | |
| | | 602 | | // Indicates that SerializeHandler is populated. |
| | 0 | 603 | | internal bool HasSerializeHandler { get; private protected set; } |
| | | 604 | | |
| | | 605 | | // Indicates that SerializeHandler is populated and is compatible with the associated contract metadata. |
| | 0 | 606 | | internal bool CanUseSerializeHandler { get; private set; } |
| | | 607 | | |
| | | 608 | | // Configure would normally have thrown why initializing properties for source gen but type had SerializeHandler |
| | | 609 | | // so it is allowed to be used for fast-path serialization but it will throw if used for metadata-based serializ |
| | 0 | 610 | | internal bool PropertyMetadataSerializationNotSupported { get; set; } |
| | | 611 | | |
| | 0 | 612 | | internal bool IsNullable => Converter.NullableElementConverter is not null; |
| | | 613 | | internal bool CanBeNull => PropertyInfoForTypeInfo.PropertyTypeCanBeNull; |
| | | 614 | | |
| | | 615 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 616 | | internal void ValidateCanBeUsedForPropertyMetadataSerialization() |
| | 0 | 617 | | { |
| | 0 | 618 | | if (PropertyMetadataSerializationNotSupported) |
| | 0 | 619 | | { |
| | 0 | 620 | | ThrowHelper.ThrowInvalidOperationException_NoMetadataForTypeProperties(Options.TypeInfoResolver, Type); |
| | | 621 | | } |
| | 0 | 622 | | } |
| | | 623 | | |
| | | 624 | | /// <summary> |
| | | 625 | | /// Return the JsonTypeInfo for the element type, or null if the type is not an enumerable or dictionary. |
| | | 626 | | /// </summary> |
| | | 627 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 628 | | internal JsonTypeInfo? ElementTypeInfo |
| | | 629 | | { |
| | | 630 | | get |
| | 0 | 631 | | { |
| | 0 | 632 | | Debug.Assert(IsConfigured); |
| | 0 | 633 | | Debug.Assert(_elementTypeInfo is null or { IsConfigurationStarted: true }); |
| | | 634 | | // Even though this instance has already been configured, |
| | | 635 | | // it is possible for contending threads to call the property |
| | | 636 | | // while the wider JsonTypeInfo graph is still being configured. |
| | | 637 | | // Call EnsureConfigured() to force synchronization if necessary. |
| | 0 | 638 | | JsonTypeInfo? elementTypeInfo = _elementTypeInfo; |
| | 0 | 639 | | elementTypeInfo?.EnsureConfigured(); |
| | 0 | 640 | | return elementTypeInfo; |
| | 0 | 641 | | } |
| | | 642 | | set |
| | 0 | 643 | | { |
| | 0 | 644 | | Debug.Assert(!IsReadOnly); |
| | 0 | 645 | | Debug.Assert(value is null || value.Type == ElementType); |
| | 0 | 646 | | _elementTypeInfo = value; |
| | 0 | 647 | | } |
| | | 648 | | } |
| | | 649 | | |
| | | 650 | | /// <summary> |
| | | 651 | | /// Return the JsonTypeInfo for the key type, or null if the type is not a dictionary. |
| | | 652 | | /// </summary> |
| | | 653 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 654 | | internal JsonTypeInfo? KeyTypeInfo |
| | | 655 | | { |
| | | 656 | | get |
| | 0 | 657 | | { |
| | 0 | 658 | | Debug.Assert(IsConfigured); |
| | 0 | 659 | | Debug.Assert(_keyTypeInfo is null or { IsConfigurationStarted: true }); |
| | | 660 | | // Even though this instance has already been configured, |
| | | 661 | | // it is possible for contending threads to call the property |
| | | 662 | | // while the wider JsonTypeInfo graph is still being configured. |
| | | 663 | | // Call EnsureConfigured() to force synchronization if necessary. |
| | 0 | 664 | | JsonTypeInfo? keyTypeInfo = _keyTypeInfo; |
| | 0 | 665 | | keyTypeInfo?.EnsureConfigured(); |
| | 0 | 666 | | return keyTypeInfo; |
| | 0 | 667 | | } |
| | | 668 | | set |
| | 0 | 669 | | { |
| | 0 | 670 | | Debug.Assert(!IsReadOnly); |
| | 0 | 671 | | Debug.Assert(value is null || value.Type == KeyType); |
| | 0 | 672 | | _keyTypeInfo = value; |
| | 0 | 673 | | } |
| | | 674 | | } |
| | | 675 | | |
| | | 676 | | private JsonTypeInfo? _elementTypeInfo; |
| | | 677 | | private JsonTypeInfo? _keyTypeInfo; |
| | | 678 | | |
| | | 679 | | /// <summary> |
| | | 680 | | /// Gets the <see cref="JsonSerializerOptions"/> value associated with the current <see cref="JsonTypeInfo" /> i |
| | | 681 | | /// </summary> |
| | 0 | 682 | | public JsonSerializerOptions Options { get; } |
| | | 683 | | |
| | | 684 | | /// <summary> |
| | | 685 | | /// Gets the <see cref="Type"/> for which the JSON serialization contract is being defined. |
| | | 686 | | /// </summary> |
| | 0 | 687 | | public Type Type { get; } |
| | | 688 | | |
| | | 689 | | /// <summary> |
| | | 690 | | /// Gets the <see cref="JsonConverter"/> associated with the current type. |
| | | 691 | | /// </summary> |
| | | 692 | | /// <remarks> |
| | | 693 | | /// The <see cref="JsonConverter"/> associated with the type determines the value of <see cref="Kind"/>, |
| | | 694 | | /// and by extension the types of metadata that are configurable in the current JSON contract. |
| | | 695 | | /// As such, the value of the converter cannot be changed once a <see cref="JsonTypeInfo"/> instance has been cr |
| | | 696 | | /// </remarks> |
| | 0 | 697 | | public JsonConverter Converter { get; } |
| | | 698 | | |
| | | 699 | | /// <summary> |
| | | 700 | | /// Determines the kind of contract metadata that the current instance is specifying. |
| | | 701 | | /// </summary> |
| | | 702 | | /// <remarks> |
| | | 703 | | /// The value of <see cref="Kind"/> determines what aspects of the JSON contract are configurable. |
| | | 704 | | /// For example, it is only possible to configure the <see cref="Properties"/> list for metadata |
| | | 705 | | /// of kind <see cref="JsonTypeInfoKind.Object"/>. |
| | | 706 | | /// |
| | | 707 | | /// The value of <see cref="Kind"/> is determined exclusively by the <see cref="JsonConverter"/> |
| | | 708 | | /// resolved for the current type, and cannot be changed once resolution has happened. |
| | | 709 | | /// User-defined custom converters (specified either via <see cref="JsonConverterAttribute"/> or <see cref="Json |
| | | 710 | | /// are metadata-agnostic and thus always resolve to <see cref="JsonTypeInfoKind.None"/>. |
| | | 711 | | /// </remarks> |
| | 0 | 712 | | public JsonTypeInfoKind Kind { get; } |
| | | 713 | | |
| | | 714 | | /// <summary> |
| | | 715 | | /// Dummy <see cref="JsonPropertyInfo"/> instance corresponding to the declaring type of this <see cref="JsonTyp |
| | | 716 | | /// </summary> |
| | | 717 | | /// <remarks> |
| | | 718 | | /// Used as convenience in cases where we want to serialize property-like values that do not define property met |
| | | 719 | | /// 1. a collection element type, |
| | | 720 | | /// 2. a dictionary key or value type or, |
| | | 721 | | /// 3. the property metadata for the root-level value. |
| | | 722 | | /// For example, for a property returning <see cref="List{T}"/> where T is a string, |
| | | 723 | | /// a JsonTypeInfo will be created with .Type=typeof(string) and .PropertyInfoForTypeInfo=JsonPropertyInfo{strin |
| | | 724 | | /// </remarks> |
| | 0 | 725 | | internal JsonPropertyInfo PropertyInfoForTypeInfo { get; } |
| | | 726 | | |
| | | 727 | | private protected abstract JsonPropertyInfo CreatePropertyInfoForTypeInfo(); |
| | | 728 | | |
| | | 729 | | /// <summary> |
| | | 730 | | /// Gets or sets the type-level <see cref="JsonSerializerOptions.NumberHandling"/> override. |
| | | 731 | | /// </summary> |
| | | 732 | | /// <exception cref="InvalidOperationException"> |
| | | 733 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 734 | | /// </exception> |
| | | 735 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 736 | | /// Specified an invalid <see cref="JsonNumberHandling"/> value. |
| | | 737 | | /// </exception> |
| | | 738 | | /// <remarks> |
| | | 739 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 740 | | /// the value of this callback will be mapped from any <see cref="JsonNumberHandlingAttribute"/> annotations. |
| | | 741 | | /// </remarks> |
| | | 742 | | public JsonNumberHandling? NumberHandling |
| | | 743 | | { |
| | 0 | 744 | | get => _numberHandling; |
| | | 745 | | set |
| | 0 | 746 | | { |
| | 0 | 747 | | VerifyMutable(); |
| | | 748 | | |
| | 0 | 749 | | if (value is not null && !JsonSerializer.IsValidNumberHandlingValue(value.Value)) |
| | 0 | 750 | | { |
| | 0 | 751 | | throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 752 | | } |
| | | 753 | | |
| | 0 | 754 | | _numberHandling = value; |
| | 0 | 755 | | } |
| | | 756 | | } |
| | | 757 | | |
| | 0 | 758 | | internal JsonNumberHandling EffectiveNumberHandling => _numberHandling ?? Options.NumberHandling; |
| | | 759 | | private JsonNumberHandling? _numberHandling; |
| | | 760 | | |
| | | 761 | | /// <summary> |
| | | 762 | | /// Gets or sets the type-level <see cref="JsonUnmappedMemberHandling"/> override. |
| | | 763 | | /// </summary> |
| | | 764 | | /// <exception cref="InvalidOperationException"> |
| | | 765 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 766 | | /// |
| | | 767 | | /// -or- |
| | | 768 | | /// |
| | | 769 | | /// Unmapped member handling only supported for <see cref="JsonTypeInfoKind.Object"/>. |
| | | 770 | | /// </exception> |
| | | 771 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 772 | | /// Specified an invalid <see cref="JsonUnmappedMemberHandling"/> value. |
| | | 773 | | /// </exception> |
| | | 774 | | /// <remarks> |
| | | 775 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 776 | | /// the value of this callback will be mapped from any <see cref="JsonUnmappedMemberHandlingAttribute"/> annotat |
| | | 777 | | /// </remarks> |
| | | 778 | | public JsonUnmappedMemberHandling? UnmappedMemberHandling |
| | | 779 | | { |
| | 0 | 780 | | get; |
| | | 781 | | set |
| | 0 | 782 | | { |
| | 0 | 783 | | VerifyMutable(); |
| | | 784 | | |
| | 0 | 785 | | if (Kind != JsonTypeInfoKind.Object) |
| | 0 | 786 | | { |
| | 0 | 787 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 788 | | } |
| | | 789 | | |
| | 0 | 790 | | if (value is not null && !JsonSerializer.IsValidUnmappedMemberHandlingValue(value.Value)) |
| | 0 | 791 | | { |
| | 0 | 792 | | throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 793 | | } |
| | | 794 | | |
| | 0 | 795 | | field = value; |
| | 0 | 796 | | } |
| | | 797 | | } |
| | | 798 | | |
| | 0 | 799 | | internal JsonUnmappedMemberHandling EffectiveUnmappedMemberHandling { get; private set; } |
| | | 800 | | |
| | | 801 | | /// <summary> |
| | | 802 | | /// Gets or sets the preferred <see cref="JsonObjectCreationHandling"/> value for properties contained in the ty |
| | | 803 | | /// </summary> |
| | | 804 | | /// <exception cref="InvalidOperationException"> |
| | | 805 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 806 | | /// |
| | | 807 | | /// -or- |
| | | 808 | | /// |
| | | 809 | | /// Unmapped member handling only supported for <see cref="JsonTypeInfoKind.Object"/>. |
| | | 810 | | /// </exception> |
| | | 811 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 812 | | /// Specified an invalid <see cref="JsonObjectCreationHandling"/> value. |
| | | 813 | | /// </exception> |
| | | 814 | | /// <remarks> |
| | | 815 | | /// For contracts originating from <see cref="DefaultJsonTypeInfoResolver"/> or <see cref="JsonSerializerContext |
| | | 816 | | /// the value of this callback will be mapped from <see cref="JsonObjectCreationHandlingAttribute"/> annotations |
| | | 817 | | /// </remarks> |
| | | 818 | | public JsonObjectCreationHandling? PreferredPropertyObjectCreationHandling |
| | | 819 | | { |
| | 0 | 820 | | get; |
| | | 821 | | set |
| | 0 | 822 | | { |
| | 0 | 823 | | VerifyMutable(); |
| | | 824 | | |
| | 0 | 825 | | if (Kind != JsonTypeInfoKind.Object) |
| | 0 | 826 | | { |
| | 0 | 827 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(Kind); |
| | | 828 | | } |
| | | 829 | | |
| | 0 | 830 | | if (value is not null && !JsonSerializer.IsValidCreationHandlingValue(value.Value)) |
| | 0 | 831 | | { |
| | 0 | 832 | | throw new ArgumentOutOfRangeException(nameof(value)); |
| | | 833 | | } |
| | | 834 | | |
| | 0 | 835 | | field = value; |
| | 0 | 836 | | } |
| | | 837 | | } |
| | | 838 | | |
| | | 839 | | /// <summary> |
| | | 840 | | /// Gets or sets the <see cref="IJsonTypeInfoResolver"/> from which this metadata instance originated. |
| | | 841 | | /// </summary> |
| | | 842 | | /// <exception cref="InvalidOperationException"> |
| | | 843 | | /// The <see cref="JsonTypeInfo"/> instance has been locked for further modification. |
| | | 844 | | /// </exception> |
| | | 845 | | /// <remarks> |
| | | 846 | | /// Metadata used to determine the <see cref="JsonSerializerContext.GeneratedSerializerOptions"/> |
| | | 847 | | /// configuration for the current metadata instance. |
| | | 848 | | /// </remarks> |
| | | 849 | | [EditorBrowsable(EditorBrowsableState.Never)] |
| | | 850 | | public IJsonTypeInfoResolver? OriginatingResolver |
| | | 851 | | { |
| | 0 | 852 | | get; |
| | | 853 | | set |
| | 0 | 854 | | { |
| | 0 | 855 | | VerifyMutable(); |
| | | 856 | | |
| | 0 | 857 | | if (value is JsonSerializerContext) |
| | 0 | 858 | | { |
| | | 859 | | // The source generator uses this property setter to brand the metadata instance as user-unmodified. |
| | | 860 | | // Even though users could call the same property setter to unset this flag, this is generally speak |
| | | 861 | | // This flag is only used to determine fast-path invalidation, worst case scenario this would lead t |
| | 0 | 862 | | IsCustomized = false; |
| | 0 | 863 | | } |
| | | 864 | | |
| | 0 | 865 | | field = value; |
| | 0 | 866 | | } |
| | | 867 | | } |
| | | 868 | | |
| | | 869 | | /// <summary> |
| | | 870 | | /// Gets or sets an attribute provider corresponding to the deserialization constructor. |
| | | 871 | | /// </summary> |
| | | 872 | | /// <exception cref="InvalidOperationException"> |
| | | 873 | | /// The <see cref="JsonPropertyInfo"/> instance has been locked for further modification. |
| | | 874 | | /// </exception> |
| | | 875 | | /// <remarks> |
| | | 876 | | /// When resolving metadata via the built-in resolvers this will be populated with |
| | | 877 | | /// the underlying <see cref="ConstructorInfo" /> of the serialized property or field. |
| | | 878 | | /// </remarks> |
| | | 879 | | public ICustomAttributeProvider? ConstructorAttributeProvider |
| | | 880 | | { |
| | | 881 | | get |
| | 0 | 882 | | { |
| | 0 | 883 | | Func<ICustomAttributeProvider>? ctorAttrProviderFactory = Volatile.Read(ref ConstructorAttributeProvider |
| | 0 | 884 | | ICustomAttributeProvider? ctorAttrProvider = _constructorAttributeProvider; |
| | | 885 | | |
| | 0 | 886 | | if (ctorAttrProvider is null && ctorAttrProviderFactory is not null) |
| | 0 | 887 | | { |
| | 0 | 888 | | _constructorAttributeProvider = ctorAttrProvider = ctorAttrProviderFactory(); |
| | 0 | 889 | | Volatile.Write(ref ConstructorAttributeProviderFactory, null); |
| | 0 | 890 | | } |
| | | 891 | | |
| | 0 | 892 | | return ctorAttrProvider; |
| | 0 | 893 | | } |
| | | 894 | | internal set |
| | 0 | 895 | | { |
| | 0 | 896 | | Debug.Assert(!IsReadOnly); |
| | | 897 | | |
| | 0 | 898 | | _constructorAttributeProvider = value; |
| | 0 | 899 | | Volatile.Write(ref ConstructorAttributeProviderFactory, null); |
| | 0 | 900 | | } |
| | | 901 | | } |
| | | 902 | | |
| | | 903 | | // Metadata emanating from the source generator use delayed attribute provider initialization |
| | | 904 | | // ensuring that reflection metadata resolution remains pay-for-play and is trimmable. |
| | | 905 | | internal Func<ICustomAttributeProvider>? ConstructorAttributeProviderFactory; |
| | | 906 | | private ICustomAttributeProvider? _constructorAttributeProvider; |
| | | 907 | | |
| | | 908 | | internal void VerifyMutable() |
| | 0 | 909 | | { |
| | 0 | 910 | | if (IsReadOnly) |
| | 0 | 911 | | { |
| | 0 | 912 | | ThrowHelper.ThrowInvalidOperationException_TypeInfoImmutable(); |
| | | 913 | | } |
| | | 914 | | |
| | 0 | 915 | | IsCustomized = true; |
| | 0 | 916 | | } |
| | | 917 | | |
| | | 918 | | /// <summary> |
| | | 919 | | /// Indicates that the current JsonTypeInfo might contain user modifications. |
| | | 920 | | /// Defaults to true, and is only unset by the built-in contract resolvers. |
| | | 921 | | /// </summary> |
| | 0 | 922 | | internal bool IsCustomized { get; set; } = true; |
| | | 923 | | |
| | 0 | 924 | | internal bool IsConfigured => _configurationState == ConfigurationState.Configured; |
| | 0 | 925 | | internal bool IsConfigurationStarted => _configurationState is not ConfigurationState.NotConfigured; |
| | | 926 | | private volatile ConfigurationState _configurationState; |
| | | 927 | | private enum ConfigurationState : byte |
| | | 928 | | { |
| | | 929 | | NotConfigured = 0, |
| | | 930 | | Configuring = 1, |
| | | 931 | | Configured = 2 |
| | | 932 | | }; |
| | | 933 | | |
| | | 934 | | private ExceptionDispatchInfo? _cachedConfigureError; |
| | | 935 | | |
| | | 936 | | internal void EnsureConfigured() |
| | 0 | 937 | | { |
| | 0 | 938 | | if (!IsConfigured) |
| | 0 | 939 | | ConfigureSynchronized(); |
| | | 940 | | |
| | | 941 | | void ConfigureSynchronized() |
| | 0 | 942 | | { |
| | 0 | 943 | | Options.MakeReadOnly(); |
| | 0 | 944 | | MakeReadOnly(); |
| | | 945 | | |
| | 0 | 946 | | _cachedConfigureError?.Throw(); |
| | | 947 | | |
| | 0 | 948 | | lock (Options.CacheContext) |
| | 0 | 949 | | { |
| | 0 | 950 | | if (_configurationState != ConfigurationState.NotConfigured) |
| | 0 | 951 | | { |
| | | 952 | | // The value of _configurationState is either |
| | | 953 | | // 'Configuring': recursive instance configured by this thread or |
| | | 954 | | // 'Configured' : instance already configured by another thread. |
| | | 955 | | // We can safely yield the configuration operation in both cases. |
| | 0 | 956 | | return; |
| | | 957 | | } |
| | | 958 | | |
| | 0 | 959 | | _cachedConfigureError?.Throw(); |
| | | 960 | | |
| | | 961 | | try |
| | 0 | 962 | | { |
| | 0 | 963 | | _configurationState = ConfigurationState.Configuring; |
| | 0 | 964 | | Configure(); |
| | 0 | 965 | | _configurationState = ConfigurationState.Configured; |
| | 0 | 966 | | } |
| | 0 | 967 | | catch (Exception e) |
| | 0 | 968 | | { |
| | 0 | 969 | | _cachedConfigureError = ExceptionDispatchInfo.Capture(e); |
| | 0 | 970 | | _configurationState = ConfigurationState.NotConfigured; |
| | 0 | 971 | | throw; |
| | | 972 | | } |
| | 0 | 973 | | } |
| | 0 | 974 | | } |
| | 0 | 975 | | } |
| | | 976 | | |
| | | 977 | | private void Configure() |
| | 0 | 978 | | { |
| | 0 | 979 | | Debug.Assert(Monitor.IsEntered(Options.CacheContext), "Configure called directly, use EnsureConfigured which |
| | 0 | 980 | | Debug.Assert(Options.IsReadOnly); |
| | 0 | 981 | | Debug.Assert(IsReadOnly); |
| | | 982 | | |
| | 0 | 983 | | PropertyInfoForTypeInfo.Configure(); |
| | | 984 | | |
| | 0 | 985 | | if (PolymorphismOptions is not null) |
| | 0 | 986 | | { |
| | | 987 | | // This needs to be done before ConfigureProperties() is called |
| | | 988 | | // JsonPropertyInfo.Configure() must have this value available in order to detect Polymoprhic + cyclic c |
| | 0 | 989 | | PolymorphicTypeResolver = new PolymorphicTypeResolver(Options, PolymorphismOptions, Type, Converter.CanH |
| | 0 | 990 | | ConfigureTypeClassifier(); |
| | 0 | 991 | | } |
| | | 992 | | |
| | 0 | 993 | | if (Kind == JsonTypeInfoKind.Object) |
| | 0 | 994 | | { |
| | 0 | 995 | | ConfigureProperties(); |
| | | 996 | | |
| | 0 | 997 | | if (DetermineUsesParameterizedConstructor()) |
| | 0 | 998 | | { |
| | 0 | 999 | | ConfigureConstructorParameters(); |
| | 0 | 1000 | | } |
| | 0 | 1001 | | } |
| | | 1002 | | |
| | 0 | 1003 | | if (ElementType != null) |
| | 0 | 1004 | | { |
| | 0 | 1005 | | _elementTypeInfo ??= Options.GetTypeInfoInternal(ElementType); |
| | 0 | 1006 | | _elementTypeInfo.EnsureConfigured(); |
| | 0 | 1007 | | } |
| | | 1008 | | |
| | 0 | 1009 | | if (KeyType != null) |
| | 0 | 1010 | | { |
| | 0 | 1011 | | _keyTypeInfo ??= Options.GetTypeInfoInternal(KeyType); |
| | 0 | 1012 | | _keyTypeInfo.EnsureConfigured(); |
| | 0 | 1013 | | } |
| | | 1014 | | |
| | 0 | 1015 | | DetermineIsCompatibleWithCurrentOptions(); |
| | 0 | 1016 | | CanUseSerializeHandler = HasSerializeHandler && IsCompatibleWithCurrentOptions; |
| | | 1017 | | |
| | | 1018 | | // Validate union metadata before sealing. By this point, every modifier has run |
| | | 1019 | | // and any contract customization that the user wanted to apply has been applied, |
| | | 1020 | | // so the final shape of the JsonTypeInfo can be checked authoritatively. |
| | 0 | 1021 | | if (Kind is JsonTypeInfoKind.Union) |
| | 0 | 1022 | | { |
| | 0 | 1023 | | ValidateUnionContract(); |
| | 0 | 1024 | | CacheUnionNullableCaseType(); |
| | 0 | 1025 | | ConfigureTypeClassifier(); |
| | 0 | 1026 | | } |
| | | 1027 | | |
| | | 1028 | | // Build the union dispatch map after modifiers have had a chance to install |
| | | 1029 | | // a custom TypeClassifier. The classifier path bypasses the value-shape map entirely. |
| | 0 | 1030 | | if (Kind is JsonTypeInfoKind.Union && |
| | 0 | 1031 | | _typeClassifier is null && |
| | 0 | 1032 | | UnionCases.Count > 0) |
| | 0 | 1033 | | { |
| | 0 | 1034 | | BuildUnionValueTypeMap(UnionCases, Options, this); |
| | 0 | 1035 | | } |
| | 0 | 1036 | | } |
| | | 1037 | | |
| | | 1038 | | /// <summary> |
| | | 1039 | | /// Validates that a union <see cref="JsonTypeInfo"/> has a well-formed shape after |
| | | 1040 | | /// all modifiers have run: at least one declared case, plus both the constructor |
| | | 1041 | | /// and the deconstructor delegates. |
| | | 1042 | | /// </summary> |
| | | 1043 | | private void ValidateUnionContract() |
| | 0 | 1044 | | { |
| | 0 | 1045 | | Debug.Assert(Kind is JsonTypeInfoKind.Union); |
| | | 1046 | | |
| | 0 | 1047 | | if (UnionCases.Count == 0) |
| | 0 | 1048 | | { |
| | 0 | 1049 | | ThrowHelper.ThrowInvalidOperationException_UnionCasesNotPopulated(Type); |
| | | 1050 | | } |
| | | 1051 | | |
| | 0 | 1052 | | if (UnionConstructor is null) |
| | 0 | 1053 | | { |
| | 0 | 1054 | | ThrowHelper.ThrowInvalidOperationException_UnionCannotCreateValue(Type); |
| | | 1055 | | } |
| | | 1056 | | |
| | 0 | 1057 | | if (UnionDeconstructor is null) |
| | 0 | 1058 | | { |
| | 0 | 1059 | | ThrowHelper.ThrowInvalidOperationException_UnionCannotReadValue(Type); |
| | | 1060 | | } |
| | 0 | 1061 | | } |
| | | 1062 | | |
| | | 1063 | | private void CacheUnionNullableCaseType() |
| | 0 | 1064 | | { |
| | 0 | 1065 | | Debug.Assert(Kind is JsonTypeInfoKind.Union); |
| | | 1066 | | |
| | 0 | 1067 | | foreach (JsonUnionCaseInfo unionCase in UnionCases) |
| | 0 | 1068 | | { |
| | 0 | 1069 | | if (unionCase.IsNullable) |
| | 0 | 1070 | | { |
| | 0 | 1071 | | UnionNullableCaseType = unionCase.CaseType; |
| | 0 | 1072 | | return; |
| | | 1073 | | } |
| | 0 | 1074 | | } |
| | | 1075 | | |
| | 0 | 1076 | | UnionNullableCaseType = null; |
| | 0 | 1077 | | } |
| | | 1078 | | |
| | | 1079 | | private void ConfigureTypeClassifier() |
| | 0 | 1080 | | { |
| | 0 | 1081 | | Debug.Assert(Kind is JsonTypeInfoKind.Union || PolymorphismOptions is not null); |
| | | 1082 | | |
| | | 1083 | | // The classifier factory may throw, which is fine -- |
| | | 1084 | | // If invoked by the getter ahead of configure we rethrow directly, |
| | | 1085 | | // but if invoked by the configuration pipeline it captures and caches the exception. |
| | | 1086 | | |
| | 0 | 1087 | | JsonTypeClassifierFactory? factory = Volatile.Read(ref _typeClassifierFactory); |
| | 0 | 1088 | | if (!_typeClassifierResolutionPending) |
| | 0 | 1089 | | { |
| | 0 | 1090 | | return; |
| | | 1091 | | } |
| | | 1092 | | |
| | | 1093 | | JsonTypeClassifierContext ctx; |
| | 0 | 1094 | | if (Kind is JsonTypeInfoKind.Union) |
| | 0 | 1095 | | { |
| | 0 | 1096 | | Debug.Assert(UnionCases.Count > 0); |
| | 0 | 1097 | | ctx = new JsonTypeClassifierContext( |
| | 0 | 1098 | | JsonTypeClassifierKind.Union, |
| | 0 | 1099 | | this, |
| | 0 | 1100 | | new List<JsonUnionCaseInfo>(UnionCases), |
| | 0 | 1101 | | Array.Empty<JsonDerivedType>(), |
| | 0 | 1102 | | typeDiscriminatorPropertyName: null); |
| | 0 | 1103 | | } |
| | | 1104 | | else |
| | 0 | 1105 | | { |
| | 0 | 1106 | | JsonPolymorphismOptions? polymorphismOptions = PolymorphismOptions; |
| | 0 | 1107 | | Debug.Assert(polymorphismOptions is not null); |
| | | 1108 | | |
| | 0 | 1109 | | ctx = new JsonTypeClassifierContext( |
| | 0 | 1110 | | JsonTypeClassifierKind.PolymorphicType, |
| | 0 | 1111 | | this, |
| | 0 | 1112 | | Array.Empty<JsonUnionCaseInfo>(), |
| | 0 | 1113 | | new List<JsonDerivedType>(polymorphismOptions.DerivedTypes), |
| | 0 | 1114 | | polymorphismOptions.TypeDiscriminatorPropertyName); |
| | 0 | 1115 | | } |
| | | 1116 | | |
| | 0 | 1117 | | if (factory is not null) |
| | 0 | 1118 | | { |
| | 0 | 1119 | | if (!factory.CanClassify(ctx)) |
| | 0 | 1120 | | { |
| | 0 | 1121 | | ThrowHelper.ThrowInvalidOperationException_TypeClassifierNotSupported(factory.GetType(), Type); |
| | | 1122 | | } |
| | 0 | 1123 | | } |
| | | 1124 | | else |
| | 0 | 1125 | | { |
| | 0 | 1126 | | factory = Options.GetTypeClassifierFromList(ctx); |
| | 0 | 1127 | | } |
| | | 1128 | | |
| | 0 | 1129 | | if (factory is not null) |
| | 0 | 1130 | | { |
| | 0 | 1131 | | JsonTypeClassifier classifier = factory.CreateJsonClassifier(ctx, Options); |
| | 0 | 1132 | | Interlocked.CompareExchange(ref _typeClassifier, classifier, null); |
| | 0 | 1133 | | } |
| | | 1134 | | |
| | 0 | 1135 | | _typeClassifierFactory = null; |
| | 0 | 1136 | | _typeClassifierResolutionPending = false; |
| | 0 | 1137 | | } |
| | | 1138 | | |
| | | 1139 | | /// <summary> |
| | | 1140 | | /// Builds the union dispatch metadata: a value-shape-to-type map for default deserialization |
| | | 1141 | | /// plus diagnostic state for cases that cannot be unambiguously classified by value shape. |
| | | 1142 | | /// </summary> |
| | | 1143 | | /// <remarks> |
| | | 1144 | | /// <para> |
| | | 1145 | | /// This helper is intentionally lenient at configuration time so that union types are |
| | | 1146 | | /// always serializable (serialization is driven by <see cref="UnionDeconstructor"/> and |
| | | 1147 | | /// doesn't need the value-shape map). Diagnostic state is recorded on the type info and |
| | | 1148 | | /// surfaced as a <see cref="JsonException"/> only at deserialization time when a token |
| | | 1149 | | /// is actually encountered that cannot be unambiguously routed to a single case. |
| | | 1150 | | /// </para> |
| | | 1151 | | /// <para> |
| | | 1152 | | /// Each case is categorized by its supported JSON value shapes via |
| | | 1153 | | /// <see cref="JsonConverter.GetSupportedJsonValueTypes"/>. User-defined converters |
| | | 1154 | | /// are conservatively classified as potentially representing every JSON value shape. |
| | | 1155 | | /// </para> |
| | | 1156 | | /// <para> |
| | | 1157 | | /// This helper operates purely on already-resolved <see cref="JsonTypeInfo"/> / |
| | | 1158 | | /// <see cref="JsonConverter"/> metadata and does not perform any reflection, so it is |
| | | 1159 | | /// safe to call from the trim-safe configuration pipeline. |
| | | 1160 | | /// </para> |
| | | 1161 | | /// </remarks> |
| | | 1162 | | private static void BuildUnionValueTypeMap(IList<JsonUnionCaseInfo> unionCases, JsonSerializerOptions options, J |
| | 0 | 1163 | | { |
| | 0 | 1164 | | var map = new Dictionary<JsonValueType, Type>(); |
| | 0 | 1165 | | JsonValueType ambiguousValueTypes = JsonValueType.None; |
| | | 1166 | | |
| | 0 | 1167 | | foreach (JsonUnionCaseInfo info in unionCases) |
| | 0 | 1168 | | { |
| | 0 | 1169 | | Type caseType = info.CaseType; |
| | 0 | 1170 | | JsonTypeInfo caseTypeInfo = options.GetTypeInfoInternal(caseType); |
| | 0 | 1171 | | JsonConverter converter = caseTypeInfo.Converter; |
| | 0 | 1172 | | if (converter.ConverterStrategy is ConverterStrategy.Union) |
| | 0 | 1173 | | { |
| | 0 | 1174 | | continue; |
| | | 1175 | | } |
| | | 1176 | | |
| | 0 | 1177 | | JsonNumberHandling effectiveNumberHandling = |
| | 0 | 1178 | | target.NumberHandling ?? caseTypeInfo.NumberHandling ?? options.NumberHandling; |
| | 0 | 1179 | | JsonValueType valueTypes = converter.GetSupportedJsonValueTypes(effectiveNumberHandling); |
| | | 1180 | | |
| | 0 | 1181 | | AddUnionValueTypes(valueTypes, caseType, map, ref ambiguousValueTypes); |
| | 0 | 1182 | | } |
| | | 1183 | | |
| | 0 | 1184 | | target.UnionValueTypeMap = map; |
| | 0 | 1185 | | target.UnionAmbiguousValueTypes = ambiguousValueTypes; |
| | | 1186 | | |
| | | 1187 | | static void AddUnionValueTypes( |
| | | 1188 | | JsonValueType valueTypes, |
| | | 1189 | | Type caseType, |
| | | 1190 | | Dictionary<JsonValueType, Type> map, |
| | | 1191 | | ref JsonValueType ambiguousValueTypes) |
| | 0 | 1192 | | { |
| | 0 | 1193 | | ReadOnlySpan<JsonValueType> allValueTypes = |
| | 0 | 1194 | | [ |
| | 0 | 1195 | | JsonValueType.Object, |
| | 0 | 1196 | | JsonValueType.Array, |
| | 0 | 1197 | | JsonValueType.String, |
| | 0 | 1198 | | JsonValueType.Number, |
| | 0 | 1199 | | JsonValueType.Boolean, |
| | 0 | 1200 | | ]; |
| | | 1201 | | |
| | 0 | 1202 | | foreach (JsonValueType valueType in allValueTypes) |
| | 0 | 1203 | | { |
| | 0 | 1204 | | if ((valueTypes & valueType) == 0) |
| | 0 | 1205 | | { |
| | 0 | 1206 | | continue; |
| | | 1207 | | } |
| | | 1208 | | |
| | 0 | 1209 | | if (!map.TryAdd(valueType, caseType)) |
| | 0 | 1210 | | { |
| | | 1211 | | // Two declared cases share this JSON value shape. First-wins for the dispatch |
| | | 1212 | | // map (so unrelated values still deserialize), but record the ambiguity |
| | | 1213 | | // so deserialize-time can throw a precise error if this shape shows up. |
| | 0 | 1214 | | ambiguousValueTypes |= valueType; |
| | 0 | 1215 | | } |
| | 0 | 1216 | | } |
| | 0 | 1217 | | } |
| | 0 | 1218 | | } |
| | | 1219 | | |
| | | 1220 | | /// <summary> |
| | | 1221 | | /// Gets any ancestor polymorphic types that declare |
| | | 1222 | | /// a type discriminator for the current type. Consulted |
| | | 1223 | | /// when serializing polymorphic values as objects. |
| | | 1224 | | /// </summary> |
| | | 1225 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 1226 | | internal JsonTypeInfo? AncestorPolymorphicType |
| | | 1227 | | { |
| | | 1228 | | get |
| | 0 | 1229 | | { |
| | 0 | 1230 | | Debug.Assert(IsConfigured); |
| | 0 | 1231 | | Debug.Assert(Type != typeof(object)); |
| | | 1232 | | |
| | 0 | 1233 | | if (!_isAncestorPolymorphicTypeResolved) |
| | 0 | 1234 | | { |
| | 0 | 1235 | | _ancestorPolymorhicType = PolymorphicTypeResolver.FindNearestPolymorphicBaseType(this); |
| | 0 | 1236 | | _isAncestorPolymorphicTypeResolved = true; |
| | 0 | 1237 | | } |
| | | 1238 | | |
| | 0 | 1239 | | return _ancestorPolymorhicType; |
| | 0 | 1240 | | } |
| | | 1241 | | } |
| | | 1242 | | |
| | | 1243 | | private JsonTypeInfo? _ancestorPolymorhicType; |
| | | 1244 | | private volatile bool _isAncestorPolymorphicTypeResolved; |
| | | 1245 | | |
| | | 1246 | | /// <summary> |
| | | 1247 | | /// Determines if the transitive closure of all JsonTypeInfo metadata referenced |
| | | 1248 | | /// by the current type (property types, key types, element types, ...) are |
| | | 1249 | | /// compatible with the settings as specified in JsonSerializerOptions. |
| | | 1250 | | /// </summary> |
| | | 1251 | | private void DetermineIsCompatibleWithCurrentOptions() |
| | 0 | 1252 | | { |
| | | 1253 | | // Defines a recursive algorithm validating that the `IsCurrentNodeCompatible` |
| | | 1254 | | // predicate is valid for every node in the type graph. This method only checks |
| | | 1255 | | // the immediate children, with recursion being driven by the Configure() method. |
| | | 1256 | | // Therefore, this method must be called _after_ the child nodes have been configured. |
| | | 1257 | | |
| | 0 | 1258 | | Debug.Assert(IsReadOnly); |
| | 0 | 1259 | | Debug.Assert(!IsConfigured); |
| | | 1260 | | |
| | 0 | 1261 | | if (!IsCurrentNodeCompatible()) |
| | 0 | 1262 | | { |
| | 0 | 1263 | | IsCompatibleWithCurrentOptions = false; |
| | 0 | 1264 | | return; |
| | | 1265 | | } |
| | | 1266 | | |
| | 0 | 1267 | | if (_properties is not null) |
| | 0 | 1268 | | { |
| | 0 | 1269 | | foreach (JsonPropertyInfo property in _properties) |
| | 0 | 1270 | | { |
| | 0 | 1271 | | Debug.Assert(property.IsConfigured); |
| | | 1272 | | |
| | 0 | 1273 | | if (!property.IsPropertyTypeInfoConfigured) |
| | 0 | 1274 | | { |
| | | 1275 | | // Either an ignored property or property is part of a cycle. |
| | | 1276 | | // In both cases we can ignore these instances. |
| | 0 | 1277 | | continue; |
| | | 1278 | | } |
| | | 1279 | | |
| | 0 | 1280 | | if (!property.JsonTypeInfo.IsCompatibleWithCurrentOptions) |
| | 0 | 1281 | | { |
| | 0 | 1282 | | IsCompatibleWithCurrentOptions = false; |
| | 0 | 1283 | | return; |
| | | 1284 | | } |
| | 0 | 1285 | | } |
| | 0 | 1286 | | } |
| | | 1287 | | |
| | 0 | 1288 | | if (_elementTypeInfo?.IsCompatibleWithCurrentOptions == false || |
| | 0 | 1289 | | _keyTypeInfo?.IsCompatibleWithCurrentOptions == false) |
| | 0 | 1290 | | { |
| | 0 | 1291 | | IsCompatibleWithCurrentOptions = false; |
| | 0 | 1292 | | return; |
| | | 1293 | | } |
| | | 1294 | | |
| | 0 | 1295 | | Debug.Assert(IsCompatibleWithCurrentOptions); |
| | | 1296 | | |
| | | 1297 | | // Defines the core predicate that must be checked for every node in the type graph. |
| | | 1298 | | bool IsCurrentNodeCompatible() |
| | 0 | 1299 | | { |
| | 0 | 1300 | | if (IsCustomized) |
| | 0 | 1301 | | { |
| | | 1302 | | // Return false if we have detected contract customization by the user. |
| | 0 | 1303 | | return false; |
| | | 1304 | | } |
| | | 1305 | | |
| | 0 | 1306 | | if (Options.CanUseFastPathSerializationLogic) |
| | 0 | 1307 | | { |
| | | 1308 | | // Simple case/backward compatibility: options uses a combination of compatible built-in converters. |
| | 0 | 1309 | | return true; |
| | | 1310 | | } |
| | | 1311 | | |
| | 0 | 1312 | | return OriginatingResolver.IsCompatibleWithOptions(Options); |
| | 0 | 1313 | | } |
| | 0 | 1314 | | } |
| | | 1315 | | |
| | | 1316 | | /// <summary> |
| | | 1317 | | /// Holds the result of the above algorithm -- NB must default to true |
| | | 1318 | | /// to establish a base case for recursive types and any JsonIgnored property types. |
| | | 1319 | | /// </summary> |
| | 0 | 1320 | | private bool IsCompatibleWithCurrentOptions { get; set; } = true; |
| | | 1321 | | |
| | | 1322 | | /// <summary> |
| | | 1323 | | /// Determine if the current configuration is compatible with using a parameterized constructor. |
| | | 1324 | | /// </summary> |
| | | 1325 | | internal bool DetermineUsesParameterizedConstructor() |
| | 0 | 1326 | | => Converter.ConstructorIsParameterized && CreateObject is null; |
| | | 1327 | | |
| | | 1328 | | /// <summary> |
| | | 1329 | | /// Creates a blank <see cref="JsonTypeInfo{T}"/> instance. |
| | | 1330 | | /// </summary> |
| | | 1331 | | /// <typeparam name="T">The type for which contract metadata is specified.</typeparam> |
| | | 1332 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> instance the metadata is associated with.</par |
| | | 1333 | | /// <returns>A blank <see cref="JsonTypeInfo{T}"/> instance.</returns> |
| | | 1334 | | /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception> |
| | | 1335 | | /// <remarks> |
| | | 1336 | | /// The returned <see cref="JsonTypeInfo{T}"/> will be blank, with the exception of the |
| | | 1337 | | /// <see cref="Converter"/> property which will be resolved either from |
| | | 1338 | | /// <see cref="JsonSerializerOptions.Converters"/> or the built-in converters for the type. |
| | | 1339 | | /// Any converters specified via <see cref="JsonConverterAttribute"/> on the type declaration |
| | | 1340 | | /// will not be resolved by this method. |
| | | 1341 | | /// |
| | | 1342 | | /// What converter does get resolved influences the value of <see cref="Kind"/>, |
| | | 1343 | | /// which constrains the type of metadata that can be modified in the <see cref="JsonTypeInfo"/> instance. |
| | | 1344 | | /// </remarks> |
| | | 1345 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1346 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1347 | | public static JsonTypeInfo<T> CreateJsonTypeInfo<T>(JsonSerializerOptions options) |
| | 0 | 1348 | | { |
| | 0 | 1349 | | ArgumentNullException.ThrowIfNull(options); |
| | | 1350 | | |
| | 0 | 1351 | | JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(typeof(T), options, resolveJsonCon |
| | 0 | 1352 | | return new JsonTypeInfo<T>(converter, options); |
| | 0 | 1353 | | } |
| | | 1354 | | |
| | | 1355 | | /// <summary> |
| | | 1356 | | /// Creates a blank <see cref="JsonTypeInfo"/> instance. |
| | | 1357 | | /// </summary> |
| | | 1358 | | /// <param name="type">The type for which contract metadata is specified.</param> |
| | | 1359 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> instance the metadata is associated with.</par |
| | | 1360 | | /// <returns>A blank <see cref="JsonTypeInfo"/> instance.</returns> |
| | | 1361 | | /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="options"/> is null.</exce |
| | | 1362 | | /// <exception cref="ArgumentException"><paramref name="type"/> cannot be used for serialization.</exception> |
| | | 1363 | | /// <remarks> |
| | | 1364 | | /// The returned <see cref="JsonTypeInfo"/> will be blank, with the exception of the |
| | | 1365 | | /// <see cref="Converter"/> property which will be resolved either from |
| | | 1366 | | /// <see cref="JsonSerializerOptions.Converters"/> or the built-in converters for the type. |
| | | 1367 | | /// Any converters specified via <see cref="JsonConverterAttribute"/> on the type declaration |
| | | 1368 | | /// will not be resolved by this method. |
| | | 1369 | | /// |
| | | 1370 | | /// What converter does get resolved influences the value of <see cref="Kind"/>, |
| | | 1371 | | /// which constrains the type of metadata that can be modified in the <see cref="JsonTypeInfo"/> instance. |
| | | 1372 | | /// </remarks> |
| | | 1373 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1374 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1375 | | public static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) |
| | 0 | 1376 | | { |
| | 0 | 1377 | | ArgumentNullException.ThrowIfNull(type); |
| | 0 | 1378 | | ArgumentNullException.ThrowIfNull(options); |
| | | 1379 | | |
| | 0 | 1380 | | if (IsInvalidForSerialization(type)) |
| | 0 | 1381 | | { |
| | 0 | 1382 | | ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(type), type, null, null); |
| | | 1383 | | } |
| | | 1384 | | |
| | 0 | 1385 | | JsonConverter converter = DefaultJsonTypeInfoResolver.GetConverterForType(type, options, resolveJsonConverte |
| | 0 | 1386 | | return CreateJsonTypeInfo(type, converter, options); |
| | 0 | 1387 | | } |
| | | 1388 | | |
| | | 1389 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1390 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1391 | | internal static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions option |
| | 0 | 1392 | | { |
| | | 1393 | | JsonTypeInfo jsonTypeInfo; |
| | | 1394 | | |
| | 0 | 1395 | | if (converter.Type == type) |
| | 0 | 1396 | | { |
| | | 1397 | | // For performance, avoid doing a reflection-based instantiation |
| | | 1398 | | // if the converter type matches that of the declared type. |
| | 0 | 1399 | | jsonTypeInfo = converter.CreateJsonTypeInfo(options); |
| | 0 | 1400 | | } |
| | | 1401 | | else |
| | 0 | 1402 | | { |
| | 0 | 1403 | | Type jsonTypeInfoType = typeof(JsonTypeInfo<>).MakeGenericType(type); |
| | 0 | 1404 | | jsonTypeInfo = (JsonTypeInfo)jsonTypeInfoType.CreateInstanceNoWrapExceptions( |
| | 0 | 1405 | | parameterTypes: [typeof(JsonConverter), typeof(JsonSerializerOptions)], |
| | 0 | 1406 | | parameters: new object[] { converter, options })!; |
| | 0 | 1407 | | } |
| | | 1408 | | |
| | 0 | 1409 | | Debug.Assert(jsonTypeInfo.Type == type); |
| | 0 | 1410 | | return jsonTypeInfo; |
| | 0 | 1411 | | } |
| | | 1412 | | |
| | | 1413 | | /// <summary> |
| | | 1414 | | /// Creates a blank <see cref="JsonPropertyInfo"/> instance for the current <see cref="JsonTypeInfo"/>. |
| | | 1415 | | /// </summary> |
| | | 1416 | | /// <param name="propertyType">The declared type for the property.</param> |
| | | 1417 | | /// <param name="name">The property name used in JSON serialization and deserialization.</param> |
| | | 1418 | | /// <returns>A blank <see cref="JsonPropertyInfo"/> instance.</returns> |
| | | 1419 | | /// <exception cref="ArgumentNullException"><paramref name="propertyType"/> or <paramref name="name"/> is null.< |
| | | 1420 | | /// <exception cref="ArgumentException"><paramref name="propertyType"/> cannot be used for serialization.</excep |
| | | 1421 | | /// <exception cref="InvalidOperationException">The <see cref="JsonTypeInfo"/> instance has been locked for furt |
| | | 1422 | | [RequiresUnreferencedCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1423 | | [RequiresDynamicCode(MetadataFactoryRequiresUnreferencedCode)] |
| | | 1424 | | public JsonPropertyInfo CreateJsonPropertyInfo(Type propertyType, string name) |
| | 0 | 1425 | | { |
| | 0 | 1426 | | ArgumentNullException.ThrowIfNull(propertyType); |
| | 0 | 1427 | | ArgumentNullException.ThrowIfNull(name); |
| | | 1428 | | |
| | 0 | 1429 | | if (IsInvalidForSerialization(propertyType)) |
| | 0 | 1430 | | { |
| | 0 | 1431 | | ThrowHelper.ThrowArgumentException_CannotSerializeInvalidType(nameof(propertyType), propertyType, Type, |
| | | 1432 | | } |
| | | 1433 | | |
| | 0 | 1434 | | VerifyMutable(); |
| | 0 | 1435 | | JsonPropertyInfo propertyInfo = CreatePropertyUsingReflection(propertyType, declaringType: null); |
| | 0 | 1436 | | propertyInfo.Name = name; |
| | | 1437 | | |
| | 0 | 1438 | | return propertyInfo; |
| | 0 | 1439 | | } |
| | | 1440 | | |
| | | 1441 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 1442 | | [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] |
| | | 1443 | | internal JsonPropertyInfo CreatePropertyUsingReflection(Type propertyType, Type? declaringType) |
| | 0 | 1444 | | { |
| | | 1445 | | JsonPropertyInfo jsonPropertyInfo; |
| | | 1446 | | |
| | 0 | 1447 | | if (Options.TryGetTypeInfoCached(propertyType, out JsonTypeInfo? jsonTypeInfo)) |
| | 0 | 1448 | | { |
| | | 1449 | | // If a JsonTypeInfo has already been cached for the property type, |
| | | 1450 | | // avoid reflection-based initialization by delegating construction |
| | | 1451 | | // of JsonPropertyInfo<T> construction to the property type metadata. |
| | 0 | 1452 | | jsonPropertyInfo = jsonTypeInfo.CreateJsonPropertyInfo(declaringTypeInfo: this, declaringType, Options); |
| | 0 | 1453 | | } |
| | | 1454 | | else |
| | 0 | 1455 | | { |
| | | 1456 | | // Metadata for `propertyType` has not been registered yet. |
| | | 1457 | | // Use reflection to instantiate the correct JsonPropertyInfo<T> |
| | 0 | 1458 | | Type propertyInfoType = typeof(JsonPropertyInfo<>).MakeGenericType(propertyType); |
| | 0 | 1459 | | jsonPropertyInfo = (JsonPropertyInfo)propertyInfoType.CreateInstanceNoWrapExceptions( |
| | 0 | 1460 | | parameterTypes: [typeof(Type), typeof(JsonTypeInfo), typeof(JsonSerializerOptions)], |
| | 0 | 1461 | | parameters: new object[] { declaringType ?? Type, this, Options })!; |
| | 0 | 1462 | | } |
| | | 1463 | | |
| | 0 | 1464 | | Debug.Assert(jsonPropertyInfo.PropertyType == propertyType); |
| | 0 | 1465 | | return jsonPropertyInfo; |
| | 0 | 1466 | | } |
| | | 1467 | | |
| | | 1468 | | /// <summary> |
| | | 1469 | | /// Creates a JsonPropertyInfo whose property type matches the type of this JsonTypeInfo instance. |
| | | 1470 | | /// </summary> |
| | | 1471 | | private protected abstract JsonPropertyInfo CreateJsonPropertyInfo(JsonTypeInfo declaringTypeInfo, Type? declari |
| | | 1472 | | |
| | | 1473 | | private protected Dictionary<ParameterLookupKey, JsonParameterInfoValues>? _parameterInfoValuesIndex; |
| | | 1474 | | |
| | | 1475 | | // Untyped, root-level serialization methods |
| | | 1476 | | internal abstract void SerializeAsObject(Utf8JsonWriter writer, object? rootValue); |
| | | 1477 | | internal abstract Task<FlushResult> SerializeAsObjectAsync(PipeWriter pipeWriter, object? rootValue, int flushTh |
| | | 1478 | | internal abstract Task SerializeAsObjectAsync(Stream utf8Json, object? rootValue, CancellationToken cancellation |
| | | 1479 | | internal abstract Task SerializeAsObjectAsync(PipeWriter utf8Json, object? rootValue, CancellationToken cancella |
| | | 1480 | | internal abstract void SerializeAsObject(Stream utf8Json, object? rootValue); |
| | | 1481 | | |
| | | 1482 | | // Untyped, root-level deserialization methods |
| | | 1483 | | internal abstract object? DeserializeAsObject(ref Utf8JsonReader reader, ref ReadStack state); |
| | | 1484 | | internal abstract ValueTask<object?> DeserializeAsObjectAsync(PipeReader utf8Json, CancellationToken cancellatio |
| | | 1485 | | internal abstract ValueTask<object?> DeserializeAsObjectAsync(Stream utf8Json, CancellationToken cancellationTok |
| | | 1486 | | internal abstract object? DeserializeAsObject(Stream utf8Json); |
| | | 1487 | | |
| | | 1488 | | internal ref struct PropertyHierarchyResolutionState(JsonSerializerOptions options) |
| | | 1489 | | { |
| | 0 | 1490 | | public Dictionary<string, (JsonPropertyInfo, int index)> AddedProperties = new(options.PropertyNameCaseInsen |
| | | 1491 | | public Dictionary<string, JsonPropertyInfo>? IgnoredProperties; |
| | | 1492 | | public bool IsPropertyOrderSpecified; |
| | | 1493 | | } |
| | | 1494 | | |
| | | 1495 | | private protected readonly struct ParameterLookupKey(Type type, string name) : IEquatable<ParameterLookupKey> |
| | | 1496 | | { |
| | 0 | 1497 | | public Type Type { get; } = type; |
| | 0 | 1498 | | public string Name { get; } = name; |
| | 0 | 1499 | | public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Name); |
| | 0 | 1500 | | public bool Equals(ParameterLookupKey other) => Type == other.Type && string.Equals(Name, other.Name, String |
| | 0 | 1501 | | public override bool Equals([NotNullWhen(true)] object? obj) => obj is ParameterLookupKey key && Equals(key) |
| | | 1502 | | } |
| | | 1503 | | |
| | | 1504 | | internal void ConfigureProperties() |
| | 0 | 1505 | | { |
| | 0 | 1506 | | Debug.Assert(Kind == JsonTypeInfoKind.Object); |
| | 0 | 1507 | | Debug.Assert(_propertyCache is null); |
| | 0 | 1508 | | Debug.Assert(_propertyIndex is null); |
| | 0 | 1509 | | Debug.Assert(ExtensionDataProperty is null); |
| | | 1510 | | |
| | 0 | 1511 | | JsonPropertyInfoList properties = PropertyList; |
| | 0 | 1512 | | StringComparer comparer = Options.PropertyNameCaseInsensitive ? StringComparer.OrdinalIgnoreCase : StringCom |
| | 0 | 1513 | | Dictionary<string, JsonPropertyInfo> propertyIndex = new(properties.Count, comparer); |
| | 0 | 1514 | | List<JsonPropertyInfo> propertyCache = new(properties.Count); |
| | | 1515 | | |
| | 0 | 1516 | | bool arePropertiesSorted = true; |
| | 0 | 1517 | | int previousPropertyOrder = int.MinValue; |
| | 0 | 1518 | | BitArray? requiredPropertiesMask = null; |
| | | 1519 | | |
| | 0 | 1520 | | for (int i = 0; i < properties.Count; i++) |
| | 0 | 1521 | | { |
| | 0 | 1522 | | JsonPropertyInfo property = properties[i]; |
| | 0 | 1523 | | Debug.Assert(property.DeclaringTypeInfo == this); |
| | | 1524 | | |
| | 0 | 1525 | | if (property.IsExtensionData) |
| | 0 | 1526 | | { |
| | 0 | 1527 | | if (UnmappedMemberHandling is JsonUnmappedMemberHandling.Disallow) |
| | 0 | 1528 | | { |
| | 0 | 1529 | | ThrowHelper.ThrowInvalidOperationException_ExtensionDataConflictsWithUnmappedMemberHandling(Type |
| | | 1530 | | } |
| | | 1531 | | |
| | 0 | 1532 | | if (ExtensionDataProperty is not null) |
| | 0 | 1533 | | { |
| | 0 | 1534 | | ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type, typeof(Json |
| | | 1535 | | } |
| | | 1536 | | |
| | 0 | 1537 | | ExtensionDataProperty = property; |
| | 0 | 1538 | | } |
| | | 1539 | | else |
| | 0 | 1540 | | { |
| | 0 | 1541 | | property.PropertyIndex = i; |
| | | 1542 | | |
| | 0 | 1543 | | if (property.IsRequired) |
| | 0 | 1544 | | { |
| | 0 | 1545 | | (requiredPropertiesMask ??= new BitArray(properties.Count))[i] = true; |
| | 0 | 1546 | | } |
| | | 1547 | | |
| | 0 | 1548 | | if (arePropertiesSorted) |
| | 0 | 1549 | | { |
| | 0 | 1550 | | arePropertiesSorted = previousPropertyOrder <= property.Order; |
| | 0 | 1551 | | previousPropertyOrder = property.Order; |
| | 0 | 1552 | | } |
| | | 1553 | | |
| | 0 | 1554 | | if (!propertyIndex.TryAdd(property.Name, property)) |
| | 0 | 1555 | | { |
| | 0 | 1556 | | ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type, property.Name); |
| | | 1557 | | } |
| | | 1558 | | |
| | 0 | 1559 | | propertyCache.Add(property); |
| | 0 | 1560 | | } |
| | | 1561 | | |
| | 0 | 1562 | | property.Configure(); |
| | 0 | 1563 | | } |
| | | 1564 | | |
| | 0 | 1565 | | if (!arePropertiesSorted) |
| | 0 | 1566 | | { |
| | | 1567 | | // Properties have been configured by the user and require sorting. |
| | 0 | 1568 | | properties.SortProperties(); |
| | 0 | 1569 | | propertyCache.StableSortByKey(static propInfo => propInfo.Order); |
| | 0 | 1570 | | } |
| | | 1571 | | |
| | 0 | 1572 | | OptionalPropertiesMask = requiredPropertiesMask?.Not(); |
| | 0 | 1573 | | _propertyCache = propertyCache.ToArray(); |
| | 0 | 1574 | | _propertyIndex = propertyIndex; |
| | | 1575 | | |
| | | 1576 | | // Override global UnmappedMemberHandling configuration |
| | | 1577 | | // if type specifies an extension data property. |
| | 0 | 1578 | | EffectiveUnmappedMemberHandling = UnmappedMemberHandling ?? |
| | 0 | 1579 | | (ExtensionDataProperty is null |
| | 0 | 1580 | | ? Options.UnmappedMemberHandling |
| | 0 | 1581 | | : JsonUnmappedMemberHandling.Skip); |
| | 0 | 1582 | | } |
| | | 1583 | | |
| | | 1584 | | internal void PopulateParameterInfoValues(JsonParameterInfoValues[] parameterInfoValues) |
| | 0 | 1585 | | { |
| | 0 | 1586 | | Dictionary<ParameterLookupKey, JsonParameterInfoValues> parameterIndex = new(parameterInfoValues.Length); |
| | 0 | 1587 | | foreach (JsonParameterInfoValues parameterInfoValue in parameterInfoValues) |
| | 0 | 1588 | | { |
| | 0 | 1589 | | ParameterLookupKey paramKey = new(parameterInfoValue.ParameterType, parameterInfoValue.Name); |
| | 0 | 1590 | | parameterIndex.TryAdd(paramKey, parameterInfoValue); // Ignore conflicts since they are reported at seri |
| | 0 | 1591 | | } |
| | | 1592 | | |
| | 0 | 1593 | | ParameterCount = parameterInfoValues.Length; |
| | 0 | 1594 | | _parameterInfoValuesIndex = parameterIndex; |
| | 0 | 1595 | | } |
| | | 1596 | | |
| | | 1597 | | internal void ResolveMatchingParameterInfo(JsonPropertyInfo propertyInfo) |
| | 0 | 1598 | | { |
| | 0 | 1599 | | Debug.Assert( |
| | 0 | 1600 | | CreateObjectWithArgs is null || _parameterInfoValuesIndex is not null, |
| | 0 | 1601 | | "Metadata with parameterized constructors must have populated parameter info metadata."); |
| | | 1602 | | |
| | 0 | 1603 | | if (_parameterInfoValuesIndex is not { } index) |
| | 0 | 1604 | | { |
| | 0 | 1605 | | return; |
| | | 1606 | | } |
| | | 1607 | | |
| | 0 | 1608 | | string propertyName = propertyInfo.MemberName ?? propertyInfo.Name; |
| | 0 | 1609 | | ParameterLookupKey propKey = new(propertyInfo.PropertyType, propertyName); |
| | 0 | 1610 | | if (index.TryGetValue(propKey, out JsonParameterInfoValues? matchingParameterInfoValues)) |
| | 0 | 1611 | | { |
| | 0 | 1612 | | propertyInfo.AddJsonParameterInfo(matchingParameterInfoValues); |
| | 0 | 1613 | | } |
| | 0 | 1614 | | } |
| | | 1615 | | |
| | | 1616 | | internal void ConfigureConstructorParameters() |
| | 0 | 1617 | | { |
| | 0 | 1618 | | Debug.Assert(Kind == JsonTypeInfoKind.Object); |
| | 0 | 1619 | | Debug.Assert(DetermineUsesParameterizedConstructor()); |
| | 0 | 1620 | | Debug.Assert(_propertyCache is not null); |
| | 0 | 1621 | | Debug.Assert(_parameterCache is null); |
| | | 1622 | | |
| | 0 | 1623 | | List<JsonParameterInfo> parameterCache = new(ParameterCount); |
| | 0 | 1624 | | Dictionary<ParameterLookupKey, JsonParameterInfo> parameterIndex = new(ParameterCount); |
| | | 1625 | | |
| | 0 | 1626 | | foreach (JsonPropertyInfo propertyInfo in _propertyCache) |
| | 0 | 1627 | | { |
| | 0 | 1628 | | JsonParameterInfo? parameterInfo = propertyInfo.AssociatedParameter; |
| | 0 | 1629 | | if (parameterInfo is null) |
| | 0 | 1630 | | { |
| | 0 | 1631 | | continue; |
| | | 1632 | | } |
| | | 1633 | | |
| | 0 | 1634 | | string propertyName = propertyInfo.MemberName ?? propertyInfo.Name; |
| | 0 | 1635 | | ParameterLookupKey paramKey = new(propertyInfo.PropertyType, propertyName); |
| | 0 | 1636 | | if (!parameterIndex.TryAdd(paramKey, parameterInfo)) |
| | 0 | 1637 | | { |
| | | 1638 | | // Multiple object properties cannot bind to the same constructor parameter. |
| | 0 | 1639 | | ThrowHelper.ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters( |
| | 0 | 1640 | | Type, |
| | 0 | 1641 | | parameterInfo.Name, |
| | 0 | 1642 | | propertyInfo.Name, |
| | 0 | 1643 | | parameterIndex[paramKey].MatchingProperty.Name); |
| | | 1644 | | } |
| | | 1645 | | |
| | 0 | 1646 | | parameterCache.Add(parameterInfo); |
| | 0 | 1647 | | } |
| | | 1648 | | |
| | 0 | 1649 | | if (ExtensionDataProperty is { AssociatedParameter: not null }) |
| | 0 | 1650 | | { |
| | 0 | 1651 | | Debug.Assert(ExtensionDataProperty.MemberName is not null, "Custom property info cannot be data extensio |
| | 0 | 1652 | | ThrowHelper.ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(ExtensionDataProperty.Memb |
| | | 1653 | | } |
| | | 1654 | | |
| | 0 | 1655 | | _parameterCache = parameterCache.ToArray(); |
| | 0 | 1656 | | _parameterInfoValuesIndex = null; |
| | 0 | 1657 | | } |
| | | 1658 | | |
| | | 1659 | | internal static void ValidateType(Type type) |
| | 0 | 1660 | | { |
| | 0 | 1661 | | if (IsInvalidForSerialization(type)) |
| | 0 | 1662 | | { |
| | 0 | 1663 | | ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(type, declaringType: null, memberI |
| | | 1664 | | } |
| | 0 | 1665 | | } |
| | | 1666 | | |
| | | 1667 | | internal static bool IsInvalidForSerialization(Type type) |
| | 0 | 1668 | | { |
| | 0 | 1669 | | return type == typeof(void) || type.IsPointer || type.IsByRef || IsByRefLike(type) || type.ContainsGenericPa |
| | 0 | 1670 | | } |
| | | 1671 | | |
| | | 1672 | | internal void MapInterfaceTypesToCallbacks() |
| | 0 | 1673 | | { |
| | 0 | 1674 | | Debug.Assert(!IsReadOnly); |
| | | 1675 | | |
| | 0 | 1676 | | if (Kind is JsonTypeInfoKind.Object or JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary) |
| | 0 | 1677 | | { |
| | 0 | 1678 | | if (typeof(IJsonOnSerializing).IsAssignableFrom(Type)) |
| | 0 | 1679 | | { |
| | 0 | 1680 | | OnSerializing = static obj => ((IJsonOnSerializing)obj).OnSerializing(); |
| | 0 | 1681 | | } |
| | | 1682 | | |
| | 0 | 1683 | | if (typeof(IJsonOnSerialized).IsAssignableFrom(Type)) |
| | 0 | 1684 | | { |
| | 0 | 1685 | | OnSerialized = static obj => ((IJsonOnSerialized)obj).OnSerialized(); |
| | 0 | 1686 | | } |
| | | 1687 | | |
| | 0 | 1688 | | if (typeof(IJsonOnDeserializing).IsAssignableFrom(Type)) |
| | 0 | 1689 | | { |
| | 0 | 1690 | | OnDeserializing = static obj => ((IJsonOnDeserializing)obj).OnDeserializing(); |
| | 0 | 1691 | | } |
| | | 1692 | | |
| | 0 | 1693 | | if (typeof(IJsonOnDeserialized).IsAssignableFrom(Type)) |
| | 0 | 1694 | | { |
| | 0 | 1695 | | OnDeserialized = static obj => ((IJsonOnDeserialized)obj).OnDeserialized(); |
| | 0 | 1696 | | } |
| | 0 | 1697 | | } |
| | 0 | 1698 | | } |
| | | 1699 | | |
| | | 1700 | | internal void SetCreateObjectIfCompatible(Delegate? createObject) |
| | 0 | 1701 | | { |
| | 0 | 1702 | | Debug.Assert(!IsReadOnly); |
| | | 1703 | | |
| | | 1704 | | // Guard against the reflection resolver/source generator attempting to pass |
| | | 1705 | | // a CreateObject delegate to converters/metadata that do not support it. |
| | 0 | 1706 | | if (Converter.SupportsCreateObjectDelegate && !Converter.ConstructorIsParameterized) |
| | 0 | 1707 | | { |
| | 0 | 1708 | | SetCreateObject(createObject); |
| | 0 | 1709 | | } |
| | 0 | 1710 | | } |
| | | 1711 | | |
| | | 1712 | | private static bool IsByRefLike(Type type) |
| | 0 | 1713 | | { |
| | | 1714 | | #if NET |
| | 0 | 1715 | | return type.IsByRefLike; |
| | | 1716 | | #else |
| | | 1717 | | if (!type.IsValueType) |
| | | 1718 | | { |
| | | 1719 | | return false; |
| | | 1720 | | } |
| | | 1721 | | |
| | | 1722 | | object[] attributes = type.GetCustomAttributes(inherit: false); |
| | | 1723 | | |
| | | 1724 | | for (int i = 0; i < attributes.Length; i++) |
| | | 1725 | | { |
| | | 1726 | | if (attributes[i].GetType().FullName == "System.Runtime.CompilerServices.IsByRefLikeAttribute") |
| | | 1727 | | { |
| | | 1728 | | return true; |
| | | 1729 | | } |
| | | 1730 | | } |
| | | 1731 | | |
| | | 1732 | | return false; |
| | | 1733 | | #endif |
| | 0 | 1734 | | } |
| | | 1735 | | |
| | | 1736 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 1737 | | internal bool SupportsPolymorphicDeserialization |
| | | 1738 | | { |
| | | 1739 | | get |
| | 0 | 1740 | | { |
| | 0 | 1741 | | Debug.Assert(IsConfigurationStarted); |
| | 0 | 1742 | | return PolymorphicTypeResolver?.UsesTypeDiscriminators == true; |
| | 0 | 1743 | | } |
| | | 1744 | | } |
| | | 1745 | | |
| | | 1746 | | internal static bool IsValidExtensionDataProperty(Type propertyType) |
| | 0 | 1747 | | { |
| | 0 | 1748 | | return typeof(IDictionary<string, object>).IsAssignableFrom(propertyType) || |
| | 0 | 1749 | | typeof(IDictionary<string, JsonElement>).IsAssignableFrom(propertyType) || |
| | 0 | 1750 | | propertyType == typeof(IReadOnlyDictionary<string, object>) || |
| | 0 | 1751 | | propertyType == typeof(IReadOnlyDictionary<string, JsonElement>) || |
| | 0 | 1752 | | // Avoid a reference to typeof(JsonNode) to support trimming. |
| | 0 | 1753 | | (propertyType.FullName == JsonObjectTypeName && ReferenceEquals(propertyType.Assembly, typeof(JsonTypeIn |
| | 0 | 1754 | | } |
| | | 1755 | | |
| | | 1756 | | private static JsonTypeInfoKind GetTypeInfoKind(Type type, JsonConverter converter) |
| | 0 | 1757 | | { |
| | 0 | 1758 | | if (type == typeof(object) && converter.CanBePolymorphic) |
| | 0 | 1759 | | { |
| | | 1760 | | // System.Object is polymorphic and will not respect Properties |
| | 0 | 1761 | | Debug.Assert(converter is ObjectConverter); |
| | 0 | 1762 | | return JsonTypeInfoKind.None; |
| | | 1763 | | } |
| | | 1764 | | |
| | 0 | 1765 | | switch (converter.ConverterStrategy) |
| | | 1766 | | { |
| | 0 | 1767 | | case ConverterStrategy.Value: return JsonTypeInfoKind.None; |
| | 0 | 1768 | | case ConverterStrategy.Object: return JsonTypeInfoKind.Object; |
| | | 1769 | | case ConverterStrategy.Union: |
| | | 1770 | | // Nullable<TUnion> delegates to the underlying union converter, but the |
| | | 1771 | | // nullable wrapper does not own union case metadata. |
| | 0 | 1772 | | return Nullable.GetUnderlyingType(type) is null ? JsonTypeInfoKind.Union : JsonTypeInfoKind.None; |
| | 0 | 1773 | | case ConverterStrategy.Enumerable: return JsonTypeInfoKind.Enumerable; |
| | 0 | 1774 | | case ConverterStrategy.Dictionary: return JsonTypeInfoKind.Dictionary; |
| | | 1775 | | case ConverterStrategy.None: |
| | 0 | 1776 | | Debug.Assert(converter is JsonConverterFactory); |
| | 0 | 1777 | | ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); |
| | | 1778 | | return default; |
| | | 1779 | | default: |
| | 0 | 1780 | | Debug.Fail($"Unexpected class type: {converter.ConverterStrategy}"); |
| | | 1781 | | throw new InvalidOperationException(); |
| | | 1782 | | } |
| | 0 | 1783 | | } |
| | | 1784 | | |
| | | 1785 | | internal sealed class JsonPropertyInfoList : ConfigurationList<JsonPropertyInfo> |
| | | 1786 | | { |
| | | 1787 | | private readonly JsonTypeInfo _jsonTypeInfo; |
| | | 1788 | | |
| | 0 | 1789 | | public JsonPropertyInfoList(JsonTypeInfo jsonTypeInfo) |
| | 0 | 1790 | | { |
| | 0 | 1791 | | _jsonTypeInfo = jsonTypeInfo; |
| | 0 | 1792 | | } |
| | | 1793 | | |
| | 0 | 1794 | | public override bool IsReadOnly => _jsonTypeInfo._properties == this && _jsonTypeInfo.IsReadOnly || _jsonTyp |
| | | 1795 | | protected override void OnCollectionModifying() |
| | 0 | 1796 | | { |
| | 0 | 1797 | | if (_jsonTypeInfo._properties == this) |
| | 0 | 1798 | | { |
| | 0 | 1799 | | _jsonTypeInfo.VerifyMutable(); |
| | 0 | 1800 | | } |
| | | 1801 | | |
| | 0 | 1802 | | if (_jsonTypeInfo.Kind != JsonTypeInfoKind.Object) |
| | 0 | 1803 | | { |
| | 0 | 1804 | | ThrowHelper.ThrowInvalidOperationException_JsonTypeInfoOperationNotPossibleForKind(_jsonTypeInfo.Kin |
| | | 1805 | | } |
| | 0 | 1806 | | } |
| | | 1807 | | |
| | | 1808 | | protected override void ValidateAddedValue(JsonPropertyInfo item) |
| | 0 | 1809 | | { |
| | 0 | 1810 | | item.EnsureChildOf(_jsonTypeInfo); |
| | 0 | 1811 | | } |
| | | 1812 | | |
| | | 1813 | | public void SortProperties() |
| | 0 | 1814 | | { |
| | 0 | 1815 | | _list.StableSortByKey(static propInfo => propInfo.Order); |
| | 0 | 1816 | | } |
| | | 1817 | | |
| | | 1818 | | /// <summary> |
| | | 1819 | | /// Used by the built-in resolvers to add property metadata applying conflict resolution. |
| | | 1820 | | /// </summary> |
| | | 1821 | | public void AddPropertyWithConflictResolution(JsonPropertyInfo jsonPropertyInfo, ref PropertyHierarchyResolu |
| | 0 | 1822 | | { |
| | 0 | 1823 | | Debug.Assert(!_jsonTypeInfo.IsConfigured); |
| | 0 | 1824 | | Debug.Assert(jsonPropertyInfo.MemberName is not null, "MemberName can be null in custom JsonPropertyInfo |
| | | 1825 | | |
| | | 1826 | | // Algorithm should be kept in sync with the Roslyn equivalent in JsonSourceGenerator.Parser.cs |
| | 0 | 1827 | | string memberName = jsonPropertyInfo.MemberName; |
| | | 1828 | | |
| | 0 | 1829 | | if (state.AddedProperties.TryAdd(jsonPropertyInfo.Name, (jsonPropertyInfo, Count))) |
| | 0 | 1830 | | { |
| | 0 | 1831 | | Add(jsonPropertyInfo); |
| | 0 | 1832 | | state.IsPropertyOrderSpecified |= jsonPropertyInfo.Order != 0; |
| | 0 | 1833 | | } |
| | | 1834 | | else |
| | 0 | 1835 | | { |
| | | 1836 | | // The JsonPropertyNameAttribute or naming policy resulted in a collision. |
| | 0 | 1837 | | (JsonPropertyInfo other, int index) = state.AddedProperties[jsonPropertyInfo.Name]; |
| | | 1838 | | |
| | 0 | 1839 | | if (other.IsIgnored) |
| | 0 | 1840 | | { |
| | | 1841 | | // Overwrite previously cached property since it has [JsonIgnore]. |
| | 0 | 1842 | | state.AddedProperties[jsonPropertyInfo.Name] = (jsonPropertyInfo, index); |
| | 0 | 1843 | | this[index] = jsonPropertyInfo; |
| | 0 | 1844 | | state.IsPropertyOrderSpecified |= jsonPropertyInfo.Order != 0; |
| | 0 | 1845 | | } |
| | | 1846 | | else |
| | 0 | 1847 | | { |
| | 0 | 1848 | | bool ignoreCurrentProperty = |
| | 0 | 1849 | | // Does the current property have `JsonIgnoreAttribute`? |
| | 0 | 1850 | | jsonPropertyInfo.IsIgnored || |
| | 0 | 1851 | | // Is the current property hidden by the previously cached property |
| | 0 | 1852 | | // (with `new` keyword, or by overriding)? |
| | 0 | 1853 | | jsonPropertyInfo.IsOverriddenOrShadowedBy(other) || |
| | 0 | 1854 | | // Was a property with the same CLR name ignored? That property hid the current property, |
| | 0 | 1855 | | // thus, if it was ignored, the current property should be ignored too. |
| | 0 | 1856 | | (state.IgnoredProperties?.TryGetValue(memberName, out JsonPropertyInfo? ignored) == true && |
| | | 1857 | | |
| | 0 | 1858 | | if (!ignoreCurrentProperty) |
| | 0 | 1859 | | { |
| | 0 | 1860 | | ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(_jsonTypeInfo.Type |
| | | 1861 | | } |
| | 0 | 1862 | | } |
| | 0 | 1863 | | } |
| | | 1864 | | |
| | 0 | 1865 | | if (jsonPropertyInfo.IsIgnored) |
| | 0 | 1866 | | { |
| | 0 | 1867 | | (state.IgnoredProperties ??= new())[memberName] = jsonPropertyInfo; |
| | 0 | 1868 | | } |
| | 0 | 1869 | | } |
| | | 1870 | | } |
| | | 1871 | | |
| | | 1872 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | 0 | 1873 | | private string DebuggerDisplay => $"Type = {Type.Name}, Kind = {Kind}"; |
| | | 1874 | | } |
| | | 1875 | | } |
| | | 1876 | | |