| | | 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.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Text.Json.Serialization.Converters; |
| | | 7 | | using System.Text.Json.Serialization.Metadata; |
| | | 8 | | |
| | | 9 | | namespace System.Text.Json.Serialization |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Converts an object or value to or from JSON. |
| | | 13 | | /// </summary> |
| | | 14 | | /// <typeparam name="T">The <see cref="System.Type"/> to convert.</typeparam> |
| | | 15 | | public abstract partial class JsonConverter<T> : JsonConverter |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// When overridden, constructs a new <see cref="JsonConverter{T}"/> instance. |
| | | 19 | | /// </summary> |
| | 2874 | 20 | | protected internal JsonConverter() |
| | 2874 | 21 | | { |
| | 2874 | 22 | | IsValueType = typeof(T).IsValueType; |
| | | 23 | | |
| | 2874 | 24 | | if (HandleNull) |
| | 3 | 25 | | { |
| | 3 | 26 | | HandleNullOnRead = true; |
| | 3 | 27 | | HandleNullOnWrite = true; |
| | 3 | 28 | | } |
| | 2871 | 29 | | else if (UsesDefaultHandleNull) |
| | 570 | 30 | | { |
| | | 31 | | // If the type doesn't support null, allow the converter a chance to modify. |
| | | 32 | | // These semantics are backwards compatible with 3.0. |
| | 570 | 33 | | HandleNullOnRead = default(T) is not null; |
| | | 34 | | |
| | | 35 | | // The framework handles null automatically on writes. |
| | 570 | 36 | | HandleNullOnWrite = false; |
| | 570 | 37 | | } |
| | 2874 | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Determines whether the type can be converted. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <remarks> |
| | | 44 | | /// The default implementation is to return True when <paramref name="typeToConvert"/> equals typeof(T). |
| | | 45 | | /// </remarks> |
| | | 46 | | /// <param name="typeToConvert"></param> |
| | | 47 | | /// <returns>True if the type can be converted, False otherwise.</returns> |
| | | 48 | | public override bool CanConvert(Type typeToConvert) |
| | 0 | 49 | | { |
| | 0 | 50 | | return typeToConvert == typeof(T); |
| | 0 | 51 | | } |
| | | 52 | | |
| | 572 | 53 | | private protected override ConverterStrategy GetDefaultConverterStrategy() => ConverterStrategy.Value; |
| | | 54 | | |
| | | 55 | | internal sealed override JsonTypeInfo CreateJsonTypeInfo(JsonSerializerOptions options) |
| | 12254 | 56 | | { |
| | 12254 | 57 | | return new JsonTypeInfo<T>(this, options); |
| | 12254 | 58 | | } |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// Indicates whether <see langword="null"/> should be passed to the converter on serialization, |
| | | 62 | | /// and whether <see cref="JsonTokenType.Null"/> should be passed on deserialization. |
| | | 63 | | /// </summary> |
| | | 64 | | /// <remarks> |
| | | 65 | | /// The default value is <see langword="true"/> for converters based on value types, and <see langword="false"/> |
| | | 66 | | /// </remarks> |
| | | 67 | | public virtual bool HandleNull |
| | | 68 | | { |
| | | 69 | | get |
| | 570 | 70 | | { |
| | 570 | 71 | | UsesDefaultHandleNull = true; |
| | 570 | 72 | | return false; |
| | 570 | 73 | | } |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | // This non-generic API is sealed as it just forwards to the generic version. |
| | | 77 | | internal sealed override void WriteAsObject(Utf8JsonWriter writer, object? value, JsonSerializerOptions options) |
| | 0 | 78 | | { |
| | 0 | 79 | | T valueOfT = JsonSerializer.UnboxOnWrite<T>(value)!; |
| | 0 | 80 | | Write(writer, valueOfT, options); |
| | 0 | 81 | | } |
| | | 82 | | |
| | | 83 | | // This non-generic API is sealed as it just forwards to the generic version. |
| | | 84 | | internal sealed override bool OnTryWriteAsObject(Utf8JsonWriter writer, object? value, JsonSerializerOptions opt |
| | 0 | 85 | | { |
| | 0 | 86 | | T valueOfT = JsonSerializer.UnboxOnWrite<T>(value)!; |
| | 0 | 87 | | return OnTryWrite(writer, valueOfT, options, ref state); |
| | 0 | 88 | | } |
| | | 89 | | |
| | | 90 | | // This non-generic API is sealed as it just forwards to the generic version. |
| | | 91 | | internal sealed override void WriteAsPropertyNameAsObject(Utf8JsonWriter writer, object? value, JsonSerializerOp |
| | 0 | 92 | | { |
| | 0 | 93 | | T valueOfT = JsonSerializer.UnboxOnWrite<T>(value)!; |
| | 0 | 94 | | WriteAsPropertyName(writer, valueOfT, options); |
| | 0 | 95 | | } |
| | | 96 | | |
| | | 97 | | internal sealed override void WriteAsPropertyNameCoreAsObject(Utf8JsonWriter writer, object? value, JsonSerializ |
| | 0 | 98 | | { |
| | 0 | 99 | | T valueOfT = JsonSerializer.UnboxOnWrite<T>(value)!; |
| | 0 | 100 | | WriteAsPropertyNameCore(writer, valueOfT, options, isWritingExtensionDataProperty); |
| | 0 | 101 | | } |
| | | 102 | | |
| | | 103 | | internal sealed override void WriteNumberWithCustomHandlingAsObject(Utf8JsonWriter writer, object? value, JsonNu |
| | 0 | 104 | | { |
| | 0 | 105 | | T valueOfT = JsonSerializer.UnboxOnWrite<T>(value)!; |
| | 0 | 106 | | WriteNumberWithCustomHandling(writer, valueOfT, handling); |
| | 0 | 107 | | } |
| | | 108 | | |
| | | 109 | | // This non-generic API is sealed as it just forwards to the generic version. |
| | | 110 | | internal sealed override bool TryWriteAsObject(Utf8JsonWriter writer, object? value, JsonSerializerOptions optio |
| | 0 | 111 | | { |
| | 0 | 112 | | T valueOfT = JsonSerializer.UnboxOnWrite<T>(value)!; |
| | 0 | 113 | | return TryWrite(writer, valueOfT, options, ref state); |
| | 0 | 114 | | } |
| | | 115 | | |
| | | 116 | | // Provide a default implementation for value converters. |
| | | 117 | | internal virtual bool OnTryWrite(Utf8JsonWriter writer, |
| | | 118 | | #nullable disable // T may or may not be nullable depending on the derived converter's HandleNull override. |
| | | 119 | | T value, |
| | | 120 | | #nullable enable |
| | | 121 | | JsonSerializerOptions options, |
| | | 122 | | ref WriteStack state) |
| | 0 | 123 | | { |
| | 0 | 124 | | Write(writer, value, options); |
| | 0 | 125 | | return true; |
| | 0 | 126 | | } |
| | | 127 | | |
| | | 128 | | // Provide a default implementation for value converters. |
| | | 129 | | internal virtual bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, sc |
| | 0 | 130 | | { |
| | 0 | 131 | | value = Read(ref reader, typeToConvert, options); |
| | 0 | 132 | | return true; |
| | 0 | 133 | | } |
| | | 134 | | |
| | | 135 | | /// <summary> |
| | | 136 | | /// Read and convert the JSON to T. |
| | | 137 | | /// </summary> |
| | | 138 | | /// <remarks> |
| | | 139 | | /// A converter may throw any Exception, but should throw <cref>JsonException</cref> when the JSON is invalid. |
| | | 140 | | /// </remarks> |
| | | 141 | | /// <param name="reader">The <see cref="Utf8JsonReader"/> to read from.</param> |
| | | 142 | | /// <param name="typeToConvert">The <see cref="System.Type"/> being converted.</param> |
| | | 143 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> being used.</param> |
| | | 144 | | /// <returns>The value that was converted.</returns> |
| | | 145 | | /// <remarks>Note that the value of <seealso cref="HandleNull"/> determines if the converter handles null JSON t |
| | | 146 | | public abstract T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options); |
| | | 147 | | |
| | | 148 | | internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, scoped ref R |
| | 26054 | 149 | | { |
| | | 150 | | // For perf and converter simplicity, handle null here instead of forwarding to the converter. |
| | 26054 | 151 | | if (reader.TokenType == JsonTokenType.Null && !HandleNullOnRead && !state.IsContinuation) |
| | 0 | 152 | | { |
| | 0 | 153 | | if (default(T) is not null) |
| | 0 | 154 | | { |
| | 0 | 155 | | ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type); |
| | | 156 | | } |
| | | 157 | | |
| | 0 | 158 | | value = default; |
| | 0 | 159 | | isPopulatedValue = false; |
| | 0 | 160 | | return true; |
| | | 161 | | } |
| | | 162 | | |
| | 26054 | 163 | | if (ConverterStrategy == ConverterStrategy.Value) |
| | 23684 | 164 | | { |
| | | 165 | | // A value converter should never be within a continuation. |
| | 23684 | 166 | | Debug.Assert(!state.IsContinuation); |
| | | 167 | | #if !DEBUG |
| | | 168 | | // For performance, only perform validation on internal converters on debug builds. |
| | | 169 | | if (IsInternalConverter) |
| | | 170 | | { |
| | | 171 | | if (state.Current.NumberHandling != null && IsInternalConverterForNumberType) |
| | | 172 | | { |
| | | 173 | | value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value, options); |
| | | 174 | | } |
| | | 175 | | else |
| | | 176 | | { |
| | | 177 | | value = Read(ref reader, typeToConvert, options); |
| | | 178 | | } |
| | | 179 | | } |
| | | 180 | | else |
| | | 181 | | #endif |
| | 23684 | 182 | | { |
| | 23684 | 183 | | JsonTokenType originalPropertyTokenType = reader.TokenType; |
| | 23684 | 184 | | int originalPropertyDepth = reader.CurrentDepth; |
| | 23684 | 185 | | long originalPropertyBytesConsumed = reader.BytesConsumed; |
| | | 186 | | |
| | 23684 | 187 | | if (state.Current.NumberHandling != null && IsInternalConverterForNumberType) |
| | 6770 | 188 | | { |
| | 6770 | 189 | | value = ReadNumberWithCustomHandling(ref reader, state.Current.NumberHandling.Value, options); |
| | 1166 | 190 | | } |
| | | 191 | | else |
| | 16914 | 192 | | { |
| | 16914 | 193 | | value = Read(ref reader, typeToConvert, options); |
| | 2806 | 194 | | } |
| | | 195 | | |
| | 3972 | 196 | | VerifyRead( |
| | 3972 | 197 | | originalPropertyTokenType, |
| | 3972 | 198 | | originalPropertyDepth, |
| | 3972 | 199 | | originalPropertyBytesConsumed, |
| | 3972 | 200 | | isValueConverter: true, |
| | 3972 | 201 | | ref reader); |
| | 3972 | 202 | | } |
| | | 203 | | |
| | 3972 | 204 | | isPopulatedValue = false; |
| | 3972 | 205 | | return true; |
| | | 206 | | } |
| | | 207 | | |
| | 2370 | 208 | | Debug.Assert(IsInternalConverter); |
| | 2370 | 209 | | bool isContinuation = state.IsContinuation; |
| | | 210 | | bool success; |
| | | 211 | | |
| | 2370 | 212 | | if ( |
| | 2370 | 213 | | #if NET |
| | 2370 | 214 | | !typeof(T).IsValueType && |
| | 2370 | 215 | | #endif |
| | 2370 | 216 | | CanBePolymorphic) |
| | 634 | 217 | | { |
| | | 218 | | // Special case object converters since they don't |
| | | 219 | | // require the expensive ReadStack.Push()/Pop() operations. |
| | 634 | 220 | | Debug.Assert(this is ObjectConverter); |
| | 634 | 221 | | success = OnTryRead(ref reader, typeToConvert, options, ref state, out value); |
| | 428 | 222 | | Debug.Assert(success); |
| | 428 | 223 | | isPopulatedValue = false; |
| | 428 | 224 | | return true; |
| | | 225 | | } |
| | | 226 | | |
| | 1736 | 227 | | JsonPropertyInfo? propertyInfo = state.Current.JsonPropertyInfo; |
| | 1736 | 228 | | object? parentObj = state.Current.ReturnValue; |
| | | 229 | | |
| | | 230 | | #if DEBUG |
| | | 231 | | // DEBUG: ensure push/pop operations preserve stack integrity |
| | 1736 | 232 | | JsonTypeInfo originalJsonTypeInfo = state.Current.JsonTypeInfo; |
| | | 233 | | #endif |
| | 1736 | 234 | | state.Push(); |
| | 1736 | 235 | | Debug.Assert(Type == state.Current.JsonTypeInfo.Type); |
| | | 236 | | |
| | 1736 | 237 | | if (!isContinuation) |
| | 1736 | 238 | | { |
| | | 239 | | #if DEBUG |
| | | 240 | | // For performance, only perform token type validation of converters on debug builds. |
| | 1736 | 241 | | Debug.Assert(state.Current.OriginalTokenType == JsonTokenType.None); |
| | 1736 | 242 | | state.Current.OriginalTokenType = reader.TokenType; |
| | | 243 | | #endif |
| | 1736 | 244 | | Debug.Assert(state.Current.OriginalDepth == 0); |
| | 1736 | 245 | | state.Current.OriginalDepth = reader.CurrentDepth; |
| | 1736 | 246 | | } |
| | | 247 | | |
| | 1736 | 248 | | if (parentObj != null && propertyInfo != null && !propertyInfo.IsForTypeInfo) |
| | 0 | 249 | | { |
| | 0 | 250 | | state.Current.HasParentObject = true; |
| | 0 | 251 | | } |
| | | 252 | | |
| | 1736 | 253 | | success = OnTryRead(ref reader, typeToConvert, options, ref state, out value); |
| | | 254 | | #if DEBUG |
| | 34 | 255 | | if (success) |
| | 34 | 256 | | { |
| | 34 | 257 | | if (state.IsContinuation) |
| | 0 | 258 | | { |
| | | 259 | | // The resumable converter did not forward to the next converter that previously returned false. |
| | 0 | 260 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 261 | | } |
| | | 262 | | |
| | 34 | 263 | | VerifyRead( |
| | 34 | 264 | | state.Current.OriginalTokenType, |
| | 34 | 265 | | state.Current.OriginalDepth, |
| | 34 | 266 | | bytesConsumed: 0, |
| | 34 | 267 | | isValueConverter: false, |
| | 34 | 268 | | ref reader); |
| | | 269 | | |
| | | 270 | | // No need to clear state.Current.* since a stack pop will occur. |
| | 34 | 271 | | } |
| | | 272 | | #endif |
| | | 273 | | |
| | 34 | 274 | | isPopulatedValue = state.Current.IsPopulating; |
| | 34 | 275 | | state.Pop(success); |
| | | 276 | | #if DEBUG |
| | 34 | 277 | | Debug.Assert(ReferenceEquals(originalJsonTypeInfo, state.Current.JsonTypeInfo)); |
| | | 278 | | #endif |
| | 34 | 279 | | return success; |
| | 4434 | 280 | | } |
| | | 281 | | |
| | | 282 | | internal sealed override bool OnTryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOpt |
| | 0 | 283 | | { |
| | 0 | 284 | | bool success = OnTryRead(ref reader, typeToConvert, options, ref state, out T? typedValue); |
| | 0 | 285 | | value = typedValue; |
| | 0 | 286 | | return success; |
| | 0 | 287 | | } |
| | | 288 | | |
| | | 289 | | internal sealed override bool TryReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptio |
| | 0 | 290 | | { |
| | 0 | 291 | | bool success = TryRead(ref reader, typeToConvert, options, ref state, out T? typedValue, out _); |
| | 0 | 292 | | value = typedValue; |
| | 0 | 293 | | return success; |
| | 0 | 294 | | } |
| | | 295 | | |
| | | 296 | | internal sealed override object? ReadAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptio |
| | 0 | 297 | | { |
| | 0 | 298 | | T? typedValue = Read(ref reader, typeToConvert, options); |
| | 0 | 299 | | return typedValue; |
| | 0 | 300 | | } |
| | | 301 | | |
| | | 302 | | internal sealed override object? ReadAsPropertyNameAsObject(ref Utf8JsonReader reader, Type typeToConvert, JsonS |
| | 0 | 303 | | { |
| | 0 | 304 | | T typedValue = ReadAsPropertyName(ref reader, typeToConvert, options); |
| | 0 | 305 | | return typedValue; |
| | 0 | 306 | | } |
| | | 307 | | |
| | | 308 | | internal sealed override object? ReadAsPropertyNameCoreAsObject(ref Utf8JsonReader reader, Type typeToConvert, J |
| | 0 | 309 | | { |
| | 0 | 310 | | T typedValue = ReadAsPropertyNameCore(ref reader, typeToConvert, options); |
| | 0 | 311 | | return typedValue; |
| | 0 | 312 | | } |
| | | 313 | | |
| | | 314 | | internal sealed override object? ReadNumberWithCustomHandlingAsObject(ref Utf8JsonReader reader, JsonNumberHandl |
| | 0 | 315 | | { |
| | 0 | 316 | | T typedValue = ReadNumberWithCustomHandling(ref reader, handling, options); |
| | 0 | 317 | | return typedValue; |
| | 0 | 318 | | } |
| | | 319 | | |
| | | 320 | | /// <summary> |
| | | 321 | | /// Performance optimization. |
| | | 322 | | /// The 'in' modifier in 'TryWrite(in T Value)' causes boxing for Nullable{T}, so this helper avoids that. |
| | | 323 | | /// TODO: Remove this work-around once https://github.com/dotnet/runtime/issues/50915 is addressed. |
| | | 324 | | /// </summary> |
| | 0 | 325 | | private static bool IsNull(T? value) => value is null; |
| | | 326 | | |
| | | 327 | | internal bool TryWrite(Utf8JsonWriter writer, in T? value, JsonSerializerOptions options, ref WriteStack state) |
| | 0 | 328 | | { |
| | 0 | 329 | | if (writer.CurrentDepth >= options.EffectiveMaxDepth) |
| | 0 | 330 | | { |
| | 0 | 331 | | ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); |
| | | 332 | | } |
| | | 333 | | |
| | 0 | 334 | | if (default(T) is null && !HandleNullOnWrite && IsNull(value)) |
| | 0 | 335 | | { |
| | | 336 | | // We do not pass null values to converters unless HandleNullOnWrite is true. Null values for properties |
| | | 337 | | // already handled in GetMemberAndWriteJson() so we don't need to check for IgnoreNullValues here. |
| | 0 | 338 | | writer.WriteNullValue(); |
| | 0 | 339 | | return true; |
| | | 340 | | } |
| | | 341 | | |
| | 0 | 342 | | if (ConverterStrategy == ConverterStrategy.Value) |
| | 0 | 343 | | { |
| | 0 | 344 | | Debug.Assert(!state.IsContinuation); |
| | | 345 | | |
| | 0 | 346 | | int originalPropertyDepth = writer.CurrentDepth; |
| | | 347 | | |
| | 0 | 348 | | if (state.Current.NumberHandling != null && IsInternalConverterForNumberType) |
| | 0 | 349 | | { |
| | 0 | 350 | | WriteNumberWithCustomHandling(writer, value, state.Current.NumberHandling.Value); |
| | 0 | 351 | | } |
| | | 352 | | else |
| | 0 | 353 | | { |
| | 0 | 354 | | Write(writer, value, options); |
| | 0 | 355 | | } |
| | | 356 | | |
| | 0 | 357 | | VerifyWrite(originalPropertyDepth, writer); |
| | 0 | 358 | | return true; |
| | | 359 | | } |
| | | 360 | | |
| | 0 | 361 | | Debug.Assert(IsInternalConverter); |
| | 0 | 362 | | bool isContinuation = state.IsContinuation; |
| | | 363 | | bool success; |
| | | 364 | | |
| | 0 | 365 | | if ( |
| | 0 | 366 | | #if NET |
| | 0 | 367 | | // Short-circuit the check against "is not null"; treated as a constant by recent versions of the JIT. |
| | 0 | 368 | | !typeof(T).IsValueType && |
| | 0 | 369 | | #else |
| | 0 | 370 | | !IsValueType && |
| | 0 | 371 | | #endif |
| | 0 | 372 | | value is not null && |
| | 0 | 373 | | // Do not handle objects that have already been |
| | 0 | 374 | | // handled by a polymorphic converter for a base type. |
| | 0 | 375 | | state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted) |
| | 0 | 376 | | { |
| | 0 | 377 | | JsonTypeInfo jsonTypeInfo = state.PeekNestedJsonTypeInfo(); |
| | 0 | 378 | | Debug.Assert(jsonTypeInfo.Converter.Type == Type); |
| | | 379 | | |
| | 0 | 380 | | bool canBePolymorphic = CanBePolymorphic || jsonTypeInfo.PolymorphicTypeResolver is not null; |
| | 0 | 381 | | JsonConverter? polymorphicConverter = canBePolymorphic ? |
| | 0 | 382 | | ResolvePolymorphicConverter(value, jsonTypeInfo, options, ref state) : |
| | 0 | 383 | | null; |
| | | 384 | | |
| | 0 | 385 | | if (!isContinuation && options.ReferenceHandlingStrategy != JsonKnownReferenceHandler.Unspecified && |
| | 0 | 386 | | TryHandleSerializedObjectReference(writer, value, options, polymorphicConverter, ref state)) |
| | 0 | 387 | | { |
| | | 388 | | // The reference handler wrote reference metadata, serialization complete. |
| | 0 | 389 | | return true; |
| | | 390 | | } |
| | | 391 | | |
| | 0 | 392 | | if (polymorphicConverter is not null) |
| | 0 | 393 | | { |
| | 0 | 394 | | success = polymorphicConverter.TryWriteAsObject(writer, value, options, ref state); |
| | 0 | 395 | | state.Current.ExitPolymorphicConverter(success); |
| | | 396 | | |
| | 0 | 397 | | if (success) |
| | 0 | 398 | | { |
| | 0 | 399 | | if (state.Current.IsPushedReferenceForCycleDetection) |
| | 0 | 400 | | { |
| | 0 | 401 | | state.ReferenceResolver.PopReferenceForCycleDetection(); |
| | 0 | 402 | | state.Current.IsPushedReferenceForCycleDetection = false; |
| | 0 | 403 | | } |
| | 0 | 404 | | } |
| | | 405 | | |
| | 0 | 406 | | return success; |
| | | 407 | | } |
| | 0 | 408 | | } |
| | | 409 | | |
| | | 410 | | #if DEBUG |
| | | 411 | | // DEBUG: ensure push/pop operations preserve stack integrity |
| | 0 | 412 | | JsonTypeInfo originalJsonTypeInfo = state.Current.JsonTypeInfo; |
| | | 413 | | #endif |
| | 0 | 414 | | state.Push(); |
| | 0 | 415 | | Debug.Assert(Type == state.Current.JsonTypeInfo.Type); |
| | | 416 | | |
| | | 417 | | #if DEBUG |
| | | 418 | | // For performance, only perform validation on internal converters on debug builds. |
| | 0 | 419 | | if (!isContinuation) |
| | 0 | 420 | | { |
| | 0 | 421 | | Debug.Assert(state.Current.OriginalDepth == 0); |
| | 0 | 422 | | state.Current.OriginalDepth = writer.CurrentDepth; |
| | 0 | 423 | | } |
| | | 424 | | #endif |
| | 0 | 425 | | success = OnTryWrite(writer, value, options, ref state); |
| | | 426 | | #if DEBUG |
| | 0 | 427 | | if (success) |
| | 0 | 428 | | { |
| | 0 | 429 | | VerifyWrite(state.Current.OriginalDepth, writer); |
| | 0 | 430 | | } |
| | | 431 | | #endif |
| | 0 | 432 | | state.Pop(success); |
| | | 433 | | |
| | 0 | 434 | | if (success && state.Current.IsPushedReferenceForCycleDetection) |
| | 0 | 435 | | { |
| | 0 | 436 | | state.ReferenceResolver.PopReferenceForCycleDetection(); |
| | 0 | 437 | | state.Current.IsPushedReferenceForCycleDetection = false; |
| | 0 | 438 | | } |
| | | 439 | | #if DEBUG |
| | 0 | 440 | | Debug.Assert(ReferenceEquals(originalJsonTypeInfo, state.Current.JsonTypeInfo)); |
| | | 441 | | #endif |
| | 0 | 442 | | return success; |
| | 0 | 443 | | } |
| | | 444 | | |
| | | 445 | | internal bool TryWriteDataExtensionProperty(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref W |
| | 0 | 446 | | { |
| | 0 | 447 | | Debug.Assert(value != null); |
| | | 448 | | |
| | 0 | 449 | | if (!IsInternalConverter) |
| | 0 | 450 | | { |
| | 0 | 451 | | return TryWrite(writer, value, options, ref state); |
| | | 452 | | } |
| | | 453 | | |
| | 0 | 454 | | JsonDictionaryConverter<T>? dictionaryConverter = this as JsonDictionaryConverter<T> |
| | 0 | 455 | | ?? (this as JsonMetadataServicesConverter<T>)?.Converter as JsonDictionaryConverter<T>; |
| | | 456 | | |
| | 0 | 457 | | if (dictionaryConverter == null) |
| | 0 | 458 | | { |
| | | 459 | | // If not JsonDictionaryConverter<T> then we are JsonObject. |
| | | 460 | | // Avoid a type reference to JsonObject and its converter to support trimming. |
| | | 461 | | // The WriteExtensionDataValue virtual method is overridden by the JsonObject converter. |
| | 0 | 462 | | Debug.Assert(Type == typeof(Nodes.JsonObject)); |
| | 0 | 463 | | WriteExtensionDataValue(writer, value!, options); |
| | | 464 | | |
| | 0 | 465 | | return true; |
| | | 466 | | } |
| | | 467 | | |
| | 0 | 468 | | if (writer.CurrentDepth >= options.EffectiveMaxDepth) |
| | 0 | 469 | | { |
| | 0 | 470 | | ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); |
| | | 471 | | } |
| | | 472 | | |
| | 0 | 473 | | bool isContinuation = state.IsContinuation; |
| | | 474 | | bool success; |
| | | 475 | | |
| | 0 | 476 | | state.Push(); |
| | | 477 | | |
| | 0 | 478 | | if (!isContinuation) |
| | 0 | 479 | | { |
| | 0 | 480 | | Debug.Assert(state.Current.OriginalDepth == 0); |
| | 0 | 481 | | state.Current.OriginalDepth = writer.CurrentDepth; |
| | 0 | 482 | | } |
| | | 483 | | |
| | | 484 | | // Extension data properties change how dictionary key naming policies are applied. |
| | 0 | 485 | | state.Current.IsWritingExtensionDataProperty = true; |
| | 0 | 486 | | state.Current.JsonPropertyInfo = state.Current.JsonTypeInfo.ElementTypeInfo!.PropertyInfoForTypeInfo; |
| | | 487 | | |
| | 0 | 488 | | success = dictionaryConverter.OnWriteResume(writer, value, options, ref state); |
| | 0 | 489 | | if (success) |
| | 0 | 490 | | { |
| | 0 | 491 | | VerifyWrite(state.Current.OriginalDepth, writer); |
| | 0 | 492 | | } |
| | | 493 | | |
| | 0 | 494 | | state.Pop(success); |
| | | 495 | | |
| | 0 | 496 | | return success; |
| | 0 | 497 | | } |
| | | 498 | | |
| | | 499 | | /// <summary> |
| | | 500 | | /// Used to support JsonObject as an extension property in a loosely-typed, trimmable manner. |
| | | 501 | | /// </summary> |
| | | 502 | | /// <remarks> |
| | | 503 | | /// Writes the extension data contents without wrapping object braces. |
| | | 504 | | /// </remarks> |
| | | 505 | | internal virtual void WriteExtensionDataValue(Utf8JsonWriter writer, T value, JsonSerializerOptions options) |
| | 0 | 506 | | { |
| | 0 | 507 | | Debug.Fail("Should not be reachable."); |
| | | 508 | | |
| | | 509 | | throw new InvalidOperationException(); |
| | | 510 | | } |
| | | 511 | | |
| | | 512 | | /// <inheritdoc/> |
| | 37846 | 513 | | public sealed override Type Type { get; } = typeof(T); |
| | | 514 | | |
| | | 515 | | internal void VerifyRead(JsonTokenType tokenType, int depth, long bytesConsumed, bool isValueConverter, ref Utf8 |
| | 4006 | 516 | | { |
| | 4006 | 517 | | Debug.Assert(isValueConverter == (ConverterStrategy == ConverterStrategy.Value)); |
| | | 518 | | |
| | 4006 | 519 | | switch (tokenType) |
| | | 520 | | { |
| | | 521 | | case JsonTokenType.StartArray: |
| | 128 | 522 | | if (reader.TokenType != JsonTokenType.EndArray) |
| | 0 | 523 | | { |
| | 0 | 524 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 525 | | } |
| | 128 | 526 | | else if (depth != reader.CurrentDepth) |
| | 0 | 527 | | { |
| | 0 | 528 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 529 | | } |
| | | 530 | | |
| | 128 | 531 | | break; |
| | | 532 | | |
| | | 533 | | case JsonTokenType.StartObject: |
| | 0 | 534 | | if (reader.TokenType != JsonTokenType.EndObject) |
| | 0 | 535 | | { |
| | 0 | 536 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 537 | | } |
| | 0 | 538 | | else if (depth != reader.CurrentDepth) |
| | 0 | 539 | | { |
| | 0 | 540 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 541 | | } |
| | | 542 | | |
| | 0 | 543 | | break; |
| | | 544 | | |
| | | 545 | | case JsonTokenType.None: |
| | 0 | 546 | | Debug.Assert(IsRootLevelMultiContentStreamingConverter); |
| | 0 | 547 | | break; |
| | | 548 | | |
| | | 549 | | default: |
| | 3878 | 550 | | if (isValueConverter) |
| | 3878 | 551 | | { |
| | | 552 | | // A value converter should not make any reads. |
| | 3878 | 553 | | if (reader.BytesConsumed != bytesConsumed) |
| | 0 | 554 | | { |
| | 0 | 555 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 556 | | } |
| | 3878 | 557 | | } |
| | | 558 | | else |
| | 0 | 559 | | { |
| | | 560 | | // A non-value converter (object or collection) should always have Start and End tokens |
| | | 561 | | // unless it is polymorphic or supports null value reads. |
| | 0 | 562 | | if (!CanBePolymorphic && !(HandleNullOnRead && tokenType == JsonTokenType.Null)) |
| | 0 | 563 | | { |
| | 0 | 564 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 565 | | } |
| | 0 | 566 | | } |
| | | 567 | | |
| | | 568 | | // Should not be possible to change token type. |
| | 3878 | 569 | | Debug.Assert(reader.TokenType == tokenType); |
| | 3878 | 570 | | break; |
| | | 571 | | } |
| | 4006 | 572 | | } |
| | | 573 | | |
| | | 574 | | internal void VerifyWrite(int originalDepth, Utf8JsonWriter writer) |
| | 0 | 575 | | { |
| | 0 | 576 | | if (originalDepth != writer.CurrentDepth) |
| | 0 | 577 | | { |
| | 0 | 578 | | ThrowHelper.ThrowJsonException_SerializationConverterWrite(this); |
| | | 579 | | } |
| | 0 | 580 | | } |
| | | 581 | | |
| | | 582 | | /// <summary> |
| | | 583 | | /// Write the value as JSON. |
| | | 584 | | /// </summary> |
| | | 585 | | /// <remarks> |
| | | 586 | | /// A converter may throw any Exception, but should throw <cref>JsonException</cref> when the JSON |
| | | 587 | | /// cannot be created. |
| | | 588 | | /// </remarks> |
| | | 589 | | /// <param name="writer">The <see cref="Utf8JsonWriter"/> to write to.</param> |
| | | 590 | | /// <param name="value">The value to convert. Note that the value of <seealso cref="HandleNull"/> determines if |
| | | 591 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> being used.</param> |
| | | 592 | | public abstract void Write( |
| | | 593 | | Utf8JsonWriter writer, |
| | | 594 | | #nullable disable // T may or may not be nullable depending on the derived converter's HandleNull override. |
| | | 595 | | T value, |
| | | 596 | | #nullable restore |
| | | 597 | | JsonSerializerOptions options); |
| | | 598 | | |
| | | 599 | | /// <summary> |
| | | 600 | | /// Reads a dictionary key from a JSON property name. |
| | | 601 | | /// </summary> |
| | | 602 | | /// <param name="reader">The <see cref="Utf8JsonReader"/> to read from.</param> |
| | | 603 | | /// <param name="typeToConvert">The <see cref="System.Type"/> being converted.</param> |
| | | 604 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> being used.</param> |
| | | 605 | | /// <returns>The value that was converted.</returns> |
| | | 606 | | /// <remarks>Method should be overridden in custom converters of types used in deserialized dictionary keys.</re |
| | | 607 | | public virtual T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options |
| | 0 | 608 | | { |
| | | 609 | | // .NET 5 backward compatibility: hardcode the default converter for primitive key serialization. |
| | 0 | 610 | | JsonConverter<T>? fallbackConverter = GetFallbackConverterForPropertyNameSerialization(options); |
| | 0 | 611 | | if (fallbackConverter is null) |
| | 0 | 612 | | { |
| | 0 | 613 | | ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type, this); |
| | | 614 | | } |
| | | 615 | | |
| | 0 | 616 | | return fallbackConverter.ReadAsPropertyNameCore(ref reader, typeToConvert, options); |
| | 0 | 617 | | } |
| | | 618 | | |
| | | 619 | | internal virtual T ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions o |
| | 0 | 620 | | { |
| | 0 | 621 | | Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); |
| | | 622 | | |
| | 0 | 623 | | long originalBytesConsumed = reader.BytesConsumed; |
| | 0 | 624 | | T result = ReadAsPropertyName(ref reader, typeToConvert, options); |
| | 0 | 625 | | if (reader.BytesConsumed != originalBytesConsumed) |
| | 0 | 626 | | { |
| | 0 | 627 | | ThrowHelper.ThrowJsonException_SerializationConverterRead(this); |
| | | 628 | | } |
| | | 629 | | |
| | 0 | 630 | | return result; |
| | 0 | 631 | | } |
| | | 632 | | |
| | | 633 | | /// <summary> |
| | | 634 | | /// Writes a dictionary key as a JSON property name. |
| | | 635 | | /// </summary> |
| | | 636 | | /// <param name="writer">The <see cref="Utf8JsonWriter"/> to write to.</param> |
| | | 637 | | /// <param name="value">The value to convert. Note that the value of <seealso cref="HandleNull"/> determines if |
| | | 638 | | /// <param name="options">The <see cref="JsonSerializerOptions"/> being used.</param> |
| | | 639 | | /// <remarks>Method should be overridden in custom converters of types used in serialized dictionary keys.</rema |
| | | 640 | | public virtual void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions opt |
| | 0 | 641 | | { |
| | | 642 | | // .NET 5 backward compatibility: hardcode the default converter for primitive key serialization. |
| | 0 | 643 | | JsonConverter<T>? fallbackConverter = GetFallbackConverterForPropertyNameSerialization(options); |
| | 0 | 644 | | if (fallbackConverter is null) |
| | 0 | 645 | | { |
| | 0 | 646 | | ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type, this); |
| | | 647 | | } |
| | | 648 | | |
| | 0 | 649 | | fallbackConverter.WriteAsPropertyNameCore(writer, value, options, isWritingExtensionDataProperty: false); |
| | 0 | 650 | | } |
| | | 651 | | |
| | | 652 | | internal virtual void WriteAsPropertyNameCore(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptio |
| | 0 | 653 | | { |
| | 0 | 654 | | ArgumentNullException.ThrowIfNull(value); |
| | | 655 | | |
| | 0 | 656 | | if (isWritingExtensionDataProperty) |
| | 0 | 657 | | { |
| | | 658 | | // Extension data is meant as mechanism to gather unused JSON properties; |
| | | 659 | | // do not apply any custom key conversions and hardcode the default behavior. |
| | 0 | 660 | | Debug.Assert(!IsInternalConverter && Type == typeof(string)); |
| | 0 | 661 | | writer.WritePropertyName((string)(object)value!); |
| | 0 | 662 | | return; |
| | | 663 | | } |
| | | 664 | | |
| | 0 | 665 | | int originalDepth = writer.CurrentDepth; |
| | 0 | 666 | | WriteAsPropertyName(writer, value, options); |
| | 0 | 667 | | if (originalDepth != writer.CurrentDepth || writer.TokenType != JsonTokenType.PropertyName) |
| | 0 | 668 | | { |
| | 0 | 669 | | ThrowHelper.ThrowJsonException_SerializationConverterWrite(this); |
| | | 670 | | } |
| | 0 | 671 | | } |
| | | 672 | | |
| | | 673 | | // .NET 5 backward compatibility: hardcode the default converter for primitive key serialization. |
| | | 674 | | private JsonConverter<T>? GetFallbackConverterForPropertyNameSerialization(JsonSerializerOptions options) |
| | 0 | 675 | | { |
| | 0 | 676 | | JsonConverter<T>? result = null; |
| | | 677 | | |
| | | 678 | | // For consistency do not return any default converters for options instances linked to a |
| | | 679 | | // JsonSerializerContext, even if the default converters might have been rooted. |
| | 0 | 680 | | if (!IsInternalConverter && options.TypeInfoResolver is not JsonSerializerContext) |
| | 0 | 681 | | { |
| | 0 | 682 | | result = _fallbackConverterForPropertyNameSerialization; |
| | | 683 | | |
| | 0 | 684 | | if (result is null && DefaultJsonTypeInfoResolver.TryGetDefaultSimpleConverter(Type, out JsonConverter? |
| | 0 | 685 | | { |
| | 0 | 686 | | Debug.Assert(defaultConverter != this); |
| | 0 | 687 | | _fallbackConverterForPropertyNameSerialization = result = (JsonConverter<T>)defaultConverter; |
| | 0 | 688 | | } |
| | 0 | 689 | | } |
| | | 690 | | |
| | 0 | 691 | | return result; |
| | 0 | 692 | | } |
| | | 693 | | |
| | | 694 | | private JsonConverter<T>? _fallbackConverterForPropertyNameSerialization; |
| | | 695 | | |
| | | 696 | | internal virtual T ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSeri |
| | 0 | 697 | | => throw new InvalidOperationException(); |
| | | 698 | | |
| | | 699 | | internal virtual void WriteNumberWithCustomHandling(Utf8JsonWriter writer, T? value, JsonNumberHandling handling |
| | 0 | 700 | | => throw new InvalidOperationException(); |
| | | 701 | | } |
| | | 702 | | } |