< Summary

Information
Class: System.Text.Json.JsonSerializer
Assembly: System.Text.Json
File(s): File 1: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs
File 2: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs
File 3: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs
File 4: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs
File 5: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs
File 6: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs
File 7: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Pipe.cs
File 8: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs
File 9: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs
File 10: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs
File 11: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs
File 12: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs
File 13: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs
File 14: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs
File 15: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.HandleMetadata.cs
File 16: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs
File 17: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs
File 18: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs
File 19: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs
File 20: https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 1685
Coverable lines: 1685
Total lines: 5297
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 394
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
File 1: .cctor()0%220%
File 1: GetTypeInfo(...)0%440%
File 1: GetTypeInfo(...)100%110%
File 1: GetTypeInfo(...)0%220%
File 1: ValidateInputType(...)0%440%
File 1: IsValidNumberHandlingValue(...)100%110%
File 1: IsValidCreationHandlingValue(...)0%220%
File 1: IsValidUnmappedMemberHandlingValue(...)0%220%
File 1: UnboxOnRead(...)0%880%
File 1: ThrowUnableToCastValue(System.Object)0%220%
File 1: UnboxOnWrite(...)0%440%
File 1: GetOrAddListTypeInfoForRootLevelValueMode(...)0%220%
File 1: GetOrAddListTypeInfoForArrayMode(...)0%220%
File 1: GetOrAddIAsyncEnumerableTypeInfoForSerialize(...)0%220%
File 2: Deserialize(...)100%110%
File 2: Deserialize(...)100%110%
File 2: Deserialize(...)100%110%
File 2: Deserialize(...)100%110%
File 2: Deserialize(...)100%110%
File 3: Deserialize(...)100%110%
File 3: Deserialize(...)100%110%
File 3: Deserialize(...)100%110%
File 3: Deserialize(...)100%110%
File 3: Deserialize(...)100%110%
File 4: .cctor()100%110%
File 4: TryReadMetadata(...)0%1061060%
File 4: IsMetadataPropertyName(...)0%880%
File 4: GetMetadataPropertyName(...)0%28280%
File 4: TryHandleReferenceFromJsonElement(...)0%20200%
File 4: TryHandleReferenceFromJsonNode(...)0%16160%
File 4: ReadAsStringMetadataValue(System.Text.Json.Nodes.JsonNode)0%880%
File 4: ValidateMetadataForObjectConverter(...)0%220%
File 4: ValidateMetadataForArrayConverter(...)0%880%
File 4: ResolveReferenceId(...)100%110%
File 5: LookupProperty(...)0%12120%
File 5: GetPropertyName(...)0%660%
File 5: CreateExtensionDataProperty(...)0%32320%
File 6: Deserialize(...)100%110%
File 6: Deserialize(...)100%110%
File 6: Deserialize(...)100%110%
File 6: Deserialize(...)100%110%
File 6: Deserialize(...)100%110%
File 6: ReadFromNode(...)0%220%
File 6: ReadFromNodeAsObject(...)0%220%
File 7: DeserializeAsync(...)100%110%
File 7: DeserializeAsync(...)100%110%
File 7: DeserializeAsync(...)100%110%
File 7: DeserializeAsync(...)100%110%
File 7: DeserializeAsync(...)100%110%
File 7: DeserializeAsyncEnumerable(...)100%110%
File 7: DeserializeAsyncEnumerable(...)100%110%
File 7: DeserializeAsyncEnumerable(...)100%110%
File 7: DeserializeAsyncEnumerable(...)100%110%
File 7: DeserializeAsyncEnumerableCore(...)0%220%
File 7: CreateAsyncEnumerableFromArray()0%660%
File 8: Deserialize(...)100%110%
File 8: Deserialize(...)100%110%
File 8: Deserialize(...)100%110%
File 8: Deserialize(...)100%110%
File 8: Deserialize(...)100%110%
File 8: ReadFromSpan(...)0%440%
File 8: ReadFromSpanAsObject(...)0%440%
File 9: DeserializeAsync(...)100%110%
File 9: Deserialize(...)100%110%
File 9: DeserializeAsync(...)100%110%
File 9: Deserialize(...)100%110%
File 9: DeserializeAsync(...)100%110%
File 9: DeserializeAsync(...)100%110%
File 9: Deserialize(...)100%110%
File 9: Deserialize(...)100%110%
File 9: DeserializeAsync(...)100%110%
File 9: Deserialize(...)100%110%
File 9: DeserializeAsyncEnumerable(...)100%110%
File 9: DeserializeAsyncEnumerable(...)100%110%
File 9: DeserializeAsyncEnumerable(...)100%110%
File 9: DeserializeAsyncEnumerable(...)100%110%
File 9: DeserializeAsyncEnumerableCore(...)0%220%
File 9: CreateAsyncEnumerableFromArray()0%660%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: Deserialize(...)100%110%
File 10: ReadFromSpan(...)0%660%
File 10: ReadFromSpanAsObject(...)0%660%
File 11: Deserialize(...)100%110%
File 11: Deserialize(...)100%110%
File 11: Deserialize(...)100%110%
File 11: Deserialize(...)100%110%
File 11: Deserialize(...)100%110%
File 11: Read(...)0%220%
File 11: ReadAsObject(...)0%220%
File 11: GetReaderScopedToNextValue(...)0%42420%
File 12: SerializeToUtf8Bytes(...)100%110%
File 12: SerializeToUtf8Bytes(...)100%110%
File 12: SerializeToUtf8Bytes(...)100%110%
File 12: SerializeToUtf8Bytes(...)100%110%
File 12: SerializeToUtf8Bytes(...)100%110%
File 12: WriteBytes(...)100%110%
File 12: WriteBytesAsObject(...)100%110%
File 13: SerializeToDocument(...)100%110%
File 13: SerializeToDocument(...)100%110%
File 13: SerializeToDocument(...)100%110%
File 13: SerializeToDocument(...)100%110%
File 13: SerializeToDocument(...)100%110%
File 13: WriteDocument(...)100%110%
File 13: WriteDocumentAsObject(...)100%110%
File 14: SerializeToElement(...)100%110%
File 14: SerializeToElement(...)100%110%
File 14: SerializeToElement(...)100%110%
File 14: SerializeToElement(...)100%110%
File 14: SerializeToElement(...)100%110%
File 14: WriteElement(...)100%110%
File 14: WriteElementAsObject(...)100%110%
File 15: .cctor()100%110%
File 15: WriteMetadataForObject(...)0%880%
File 15: WriteMetadataForCollection(...)100%110%
File 15: TryGetReferenceForValue(...)0%220%
File 16: SerializeToNode(...)100%110%
File 16: SerializeToNode(...)100%110%
File 16: SerializeToNode(...)100%110%
File 16: SerializeToNode(...)100%110%
File 16: SerializeToNode(...)100%110%
File 16: WriteNode(...)100%110%
File 16: WriteNodeAsObject(...)100%110%
File 17: SerializeAsync(...)100%110%
File 17: SerializeAsync(...)100%110%
File 17: SerializeAsync(...)100%110%
File 17: SerializeAsync(...)100%110%
File 17: SerializeAsync(...)100%110%
File 17: SerializeAsyncEnumerable(...)0%220%
File 17: SerializeAsyncEnumerable(...)0%220%
File 17: SerializeAsyncEnumerableAsJsonLines()0%880%
File 18: SerializeAsync(...)100%110%
File 18: Serialize(...)100%110%
File 18: SerializeAsync(...)100%110%
File 18: Serialize(...)100%110%
File 18: SerializeAsync(...)100%110%
File 18: Serialize(...)100%110%
File 18: SerializeAsync(...)100%110%
File 18: Serialize(...)100%110%
File 18: SerializeAsync(...)100%110%
File 18: Serialize(...)100%110%
File 18: SerializeAsyncEnumerable(...)0%220%
File 18: SerializeAsyncEnumerable(...)0%220%
File 18: SerializeAsyncEnumerableAsJsonLines()100%110%
File 19: Serialize(...)100%110%
File 19: Serialize(...)100%110%
File 19: Serialize(...)100%110%
File 19: Serialize(...)100%110%
File 19: Serialize(...)100%110%
File 19: WriteString(...)100%110%
File 19: WriteStringAsObject(...)100%110%
File 20: Serialize(...)100%110%
File 20: Serialize(...)100%110%
File 20: Serialize(...)100%110%
File 20: Serialize(...)100%110%
File 20: Serialize(...)100%110%

File(s)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Helpers.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.Text.Json.Serialization;
 8using System.Text.Json.Serialization.Converters;
 9using System.Text.Json.Serialization.Metadata;
 10
 11namespace System.Text.Json
 12{
 13    public static partial class JsonSerializer
 14    {
 15        internal const string SerializationUnreferencedCodeMessage = "JSON serialization and deserialization might requi
 16        internal const string SerializationRequiresDynamicCodeMessage = "JSON serialization and deserialization might re
 17
 18        /// <summary>
 19        /// Indicates whether unconfigured <see cref="JsonSerializerOptions"/> instances
 20        /// should be set to use the reflection-based <see cref="DefaultJsonTypeInfoResolver"/>.
 21        /// </summary>
 22        /// <remarks>
 23        /// The value of the property is backed by the "System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault"
 24        /// <see cref="AppContext"/> setting and defaults to <see langword="true"/> if unset.
 25        /// </remarks>
 26        [FeatureSwitchDefinition("System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault")]
 027        public static bool IsReflectionEnabledByDefault { get; } =
 028            AppContext.TryGetSwitch(
 029                switchName: "System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault",
 030                isEnabled: out bool value)
 031            ? value : true;
 32
 33        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 34        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 35        private static JsonTypeInfo GetTypeInfo(JsonSerializerOptions? options, Type inputType)
 036        {
 037            Debug.Assert(inputType != null);
 38
 039            options ??= JsonSerializerOptions.Default;
 040            options.MakeReadOnly(populateMissingResolver: true);
 41
 42            // In order to improve performance of polymorphic root-level object serialization,
 43            // we bypass GetTypeInfoForRootType and cache JsonTypeInfo<object> in a dedicated property.
 44            // This lets any derived types take advantage of the cache in GetTypeInfoForRootType themselves.
 045            return inputType == typeof(object)
 046                ? options.ObjectTypeInfo
 047                : options.GetTypeInfoForRootType(inputType);
 048        }
 49
 50        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 51        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 52        private static JsonTypeInfo<T> GetTypeInfo<T>(JsonSerializerOptions? options)
 053            => (JsonTypeInfo<T>)GetTypeInfo(options, typeof(T));
 54
 55        private static JsonTypeInfo GetTypeInfo(JsonSerializerContext context, Type inputType)
 056        {
 057            Debug.Assert(context is not null);
 058            Debug.Assert(inputType != null);
 59
 060            JsonTypeInfo? info = context.GetTypeInfo(inputType);
 061            if (info is null)
 062            {
 063                ThrowHelper.ThrowInvalidOperationException_NoMetadataForType(inputType, context);
 64            }
 65
 066            info.EnsureConfigured();
 067            return info;
 068        }
 69
 70        private static void ValidateInputType(object? value, Type inputType)
 071        {
 072            ArgumentNullException.ThrowIfNull(inputType);
 73
 074            if (value is not null)
 075            {
 076                Type runtimeType = value.GetType();
 077                if (!inputType.IsAssignableFrom(runtimeType))
 078                {
 079                    ThrowHelper.ThrowArgumentException_DeserializeWrongType(inputType, value);
 80                }
 081            }
 082        }
 83
 84        internal static bool IsValidNumberHandlingValue(JsonNumberHandling handling) =>
 085            JsonHelpers.IsInRangeInclusive((int)handling, 0,
 086                (int)(
 087                JsonNumberHandling.Strict |
 088                JsonNumberHandling.AllowReadingFromString |
 089                JsonNumberHandling.WriteAsString |
 090                JsonNumberHandling.AllowNamedFloatingPointLiterals));
 91
 92        internal static bool IsValidCreationHandlingValue(JsonObjectCreationHandling handling) =>
 093            handling is JsonObjectCreationHandling.Replace or JsonObjectCreationHandling.Populate;
 94
 95        internal static bool IsValidUnmappedMemberHandlingValue(JsonUnmappedMemberHandling handling) =>
 096            handling is JsonUnmappedMemberHandling.Skip or JsonUnmappedMemberHandling.Disallow;
 97
 98        [return: NotNullIfNotNull(nameof(value))]
 99        internal static T? UnboxOnRead<T>(object? value)
 0100        {
 0101            if (value is null)
 0102            {
 0103                if (default(T) is not null)
 0104                {
 105                    // Casting null values to a non-nullable struct throws NullReferenceException.
 0106                    ThrowUnableToCastValue(value);
 0107                }
 108
 0109                return default;
 110            }
 111
 0112            if (value is T typedValue)
 0113            {
 0114                return typedValue;
 115            }
 116
 0117            ThrowUnableToCastValue(value);
 0118            return default!;
 119
 120            static void ThrowUnableToCastValue(object? value)
 0121            {
 0122                if (value is null)
 0123                {
 0124                    ThrowHelper.ThrowInvalidOperationException_DeserializeUnableToAssignNull(declaredType: typeof(T));
 125                }
 126                else
 0127                {
 0128                    ThrowHelper.ThrowInvalidCastException_DeserializeUnableToAssignValue(typeOfValue: value.GetType(), d
 129                }
 130            }
 0131        }
 132
 133        [return: NotNullIfNotNull(nameof(value))]
 134        internal static T? UnboxOnWrite<T>(object? value)
 0135        {
 0136            if (default(T) is not null && value is null)
 0137            {
 138                // Casting null values to a non-nullable struct throws NullReferenceException.
 0139                ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(typeof(T));
 140            }
 141
 0142            return (T?)value;
 0143        }
 144
 145        private static JsonTypeInfo<List<T?>> GetOrAddListTypeInfoForRootLevelValueMode<T>(JsonTypeInfo<T> elementTypeIn
 0146        {
 0147            if (elementTypeInfo._asyncEnumerableRootLevelValueTypeInfo is not null)
 0148            {
 0149                return (JsonTypeInfo<List<T?>>)elementTypeInfo._asyncEnumerableRootLevelValueTypeInfo;
 150            }
 151
 0152            var converter = new RootLevelListConverter<T>(elementTypeInfo);
 0153            var listTypeInfo = new JsonTypeInfo<List<T?>>(converter, elementTypeInfo.Options)
 0154            {
 0155                ElementTypeInfo = elementTypeInfo,
 0156            };
 157
 0158            listTypeInfo.EnsureConfigured();
 0159            elementTypeInfo._asyncEnumerableRootLevelValueTypeInfo = listTypeInfo;
 0160            return listTypeInfo;
 0161        }
 162
 163        private static JsonTypeInfo<List<T?>> GetOrAddListTypeInfoForArrayMode<T>(JsonTypeInfo<T> elementTypeInfo)
 0164        {
 0165            if (elementTypeInfo._asyncEnumerableArrayTypeInfo is not null)
 0166            {
 0167                return (JsonTypeInfo<List<T?>>)elementTypeInfo._asyncEnumerableArrayTypeInfo;
 168            }
 169
 0170            var converter = new ListOfTConverter<List<T>, T>();
 0171            var listTypeInfo = new JsonTypeInfo<List<T?>>(converter, elementTypeInfo.Options)
 0172            {
 0173                CreateObject = static () => new List<T?>(),
 0174                ElementTypeInfo = elementTypeInfo,
 0175            };
 176
 0177            listTypeInfo.EnsureConfigured();
 0178            elementTypeInfo._asyncEnumerableArrayTypeInfo = listTypeInfo;
 0179            return listTypeInfo;
 0180        }
 181
 182        private static JsonTypeInfo<IAsyncEnumerable<T>> GetOrAddIAsyncEnumerableTypeInfoForSerialize<T>(JsonTypeInfo<T>
 0183        {
 0184            if (elementTypeInfo._asyncEnumerableRootLevelSerializer is not null)
 0185            {
 0186                return (JsonTypeInfo<IAsyncEnumerable<T>>)elementTypeInfo._asyncEnumerableRootLevelSerializer;
 187            }
 188
 189            // Synthesize the IAsyncEnumerable<T> type info from the element type info so we don't depend on the
 190            // resolver (e.g. a source-generated context) having registered IAsyncEnumerable<T> explicitly.
 0191            var converter = new IAsyncEnumerableOfTConverter<IAsyncEnumerable<T>, T>();
 0192            var asyncEnumerableTypeInfo = new JsonTypeInfo<IAsyncEnumerable<T>>(converter, elementTypeInfo.Options)
 0193            {
 0194                ElementTypeInfo = elementTypeInfo,
 0195            };
 196
 0197            asyncEnumerableTypeInfo.EnsureConfigured();
 0198            elementTypeInfo._asyncEnumerableRootLevelSerializer = asyncEnumerableTypeInfo;
 0199            return asyncEnumerableTypeInfo;
 0200        }
 201    }
 202}
 203

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs

#LineLine coverage
 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
 4using System.Diagnostics.CodeAnalysis;
 5using System.Text.Json.Serialization;
 6using System.Text.Json.Serialization.Metadata;
 7
 8namespace System.Text.Json
 9{
 10    public static partial class JsonSerializer
 11    {
 12        /// <summary>
 13        /// Converts the <see cref="JsonDocument"/> representing a single JSON value into a <typeparamref name="TValue"/
 14        /// </summary>
 15        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 16        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 17        /// <param name="document">The <see cref="JsonDocument"/> to convert.</param>
 18        /// <param name="options">Options to control the behavior during parsing.</param>
 19        /// <exception cref="System.ArgumentNullException">
 20        /// <paramref name="document"/> is <see langword="null"/>.
 21        /// </exception>
 22        /// <exception cref="JsonException">
 23        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 24        /// </exception>
 25        /// <exception cref="NotSupportedException">
 26        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 27        /// for <typeparamref name="TValue"/> or its serializable members.
 28        /// </exception>
 29        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 30        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 31        public static TValue? Deserialize<TValue>(this JsonDocument document, JsonSerializerOptions? options = null)
 032        {
 033            ArgumentNullException.ThrowIfNull(document);
 34
 035            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 036            ReadOnlySpan<byte> utf8Json = document.GetRootRawValue().Span;
 037            return ReadFromSpan(utf8Json, jsonTypeInfo);
 038        }
 39
 40        /// <summary>
 41        /// Converts the <see cref="JsonDocument"/> representing a single JSON value into a <paramref name="returnType"/
 42        /// </summary>
 43        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 44        /// <param name="document">The <see cref="JsonDocument"/> to convert.</param>
 45        /// <param name="returnType">The type of the object to convert to and return.</param>
 46        /// <param name="options">Options to control the behavior during parsing.</param>
 47        /// <exception cref="System.ArgumentNullException">
 48        /// <paramref name="document"/> or <paramref name="returnType"/> is <see langword="null"/>.
 49        /// </exception>
 50        /// <exception cref="JsonException">
 51        /// <paramref name="returnType"/> is not compatible with the JSON.
 52        /// </exception>
 53        /// <exception cref="NotSupportedException">
 54        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 55        /// for <paramref name="returnType"/> or its serializable members.
 56        /// </exception>
 57        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 58        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 59        public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = 
 060        {
 061            ArgumentNullException.ThrowIfNull(document);
 062            ArgumentNullException.ThrowIfNull(returnType);
 63
 064            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 065            ReadOnlySpan<byte> utf8Json = document.GetRootRawValue().Span;
 066            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 067        }
 68
 69        /// <summary>
 70        /// Converts the <see cref="JsonDocument"/> representing a single JSON value into a <typeparamref name="TValue"/
 71        /// </summary>
 72        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 73        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 74        /// <param name="document">The <see cref="JsonDocument"/> to convert.</param>
 75        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 76        /// <exception cref="System.ArgumentNullException">
 77        /// <paramref name="document"/> is <see langword="null"/>.
 78        ///
 79        /// -or-
 80        ///
 81        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 82        /// </exception>
 83        /// <exception cref="JsonException">
 84        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 85        /// </exception>
 86        public static TValue? Deserialize<TValue>(this JsonDocument document, JsonTypeInfo<TValue> jsonTypeInfo)
 087        {
 088            ArgumentNullException.ThrowIfNull(document);
 089            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 90
 091            jsonTypeInfo.EnsureConfigured();
 092            ReadOnlySpan<byte> utf8Json = document.GetRootRawValue().Span;
 093            return ReadFromSpan(utf8Json, jsonTypeInfo);
 094        }
 95
 96        /// <summary>
 97        /// Converts the <see cref="JsonDocument"/> representing a single JSON value into an instance specified by the <
 98        /// </summary>
 99        /// <param name="document">The <see cref="JsonDocument"/> to convert.</param>
 100        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 101        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 102        /// <exception cref="System.ArgumentNullException">
 103        /// <paramref name="document"/> is <see langword="null"/>.
 104        ///
 105        /// -or-
 106        ///
 107        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 108        /// </exception>
 109        public static object? Deserialize(this JsonDocument document, JsonTypeInfo jsonTypeInfo)
 0110        {
 0111            ArgumentNullException.ThrowIfNull(document);
 0112            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 113
 0114            jsonTypeInfo.EnsureConfigured();
 0115            ReadOnlySpan<byte> utf8Json = document.GetRootRawValue().Span;
 0116            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 0117        }
 118
 119        /// <summary>
 120        /// Converts the <see cref="JsonDocument"/> representing a single JSON value into a <paramref name="returnType"/
 121        /// </summary>
 122        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 123        /// <param name="document">The <see cref="JsonDocument"/> to convert.</param>
 124        /// <param name="returnType">The type of the object to convert to and return.</param>
 125        /// <param name="context">A metadata provider for serializable types.</param>
 126        /// <exception cref="System.ArgumentNullException">
 127        /// <paramref name="document"/> is <see langword="null"/>.
 128        ///
 129        /// -or-
 130        ///
 131        /// <paramref name="returnType"/> is <see langword="null"/>.
 132        ///
 133        /// -or-
 134        ///
 135        /// <paramref name="context"/> is <see langword="null"/>.
 136        /// </exception>
 137        /// <exception cref="JsonException">
 138        /// The JSON is invalid.
 139        ///
 140        /// -or-
 141        ///
 142        /// <paramref name="returnType" /> is not compatible with the JSON.
 143        ///
 144        /// -or-
 145        ///
 146        /// There is remaining data in the string beyond a single JSON value.</exception>
 147        /// <exception cref="NotSupportedException">
 148        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 149        /// for <paramref name="returnType"/> or its serializable members.
 150        /// </exception>
 151        /// <exception cref="InvalidOperationException">
 152        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 153        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 154        /// </exception>
 155        public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerContext context)
 0156        {
 0157            ArgumentNullException.ThrowIfNull(document);
 0158            ArgumentNullException.ThrowIfNull(returnType);
 0159            ArgumentNullException.ThrowIfNull(context);
 160
 0161            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0162            ReadOnlySpan<byte> utf8Json = document.GetRootRawValue().Span;
 0163            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 0164        }
 165    }
 166}
 167

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs

#LineLine coverage
 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
 4using System.Diagnostics.CodeAnalysis;
 5using System.Text.Json.Serialization;
 6using System.Text.Json.Serialization.Metadata;
 7
 8namespace System.Text.Json
 9{
 10    public static partial class JsonSerializer
 11    {
 12        /// <summary>
 13        /// Converts the <see cref="JsonElement"/> representing a single JSON value into a <typeparamref name="TValue"/>
 14        /// </summary>
 15        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 16        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 17        /// <param name="element">The <see cref="JsonElement"/> to convert.</param>
 18        /// <param name="options">Options to control the behavior during parsing.</param>
 19        /// <exception cref="JsonException">
 20        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 21        /// </exception>
 22        /// <exception cref="NotSupportedException">
 23        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 24        /// for <typeparamref name="TValue"/> or its serializable members.
 25        /// </exception>
 26        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 27        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 28        public static TValue? Deserialize<TValue>(this JsonElement element, JsonSerializerOptions? options = null)
 029        {
 030            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 031            ReadOnlySpan<byte> utf8Json = element.GetRawValue().Span;
 032            return ReadFromSpan(utf8Json, jsonTypeInfo);
 033        }
 34
 35        /// <summary>
 36        /// Converts the <see cref="JsonElement"/> representing a single JSON value into a <paramref name="returnType"/>
 37        /// </summary>
 38        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 39        /// <param name="element">The <see cref="JsonElement"/> to convert.</param>
 40        /// <param name="returnType">The type of the object to convert to and return.</param>
 41        /// <param name="options">Options to control the behavior during parsing.</param>
 42        /// <exception cref="System.ArgumentNullException">
 43        /// <paramref name="returnType"/> is <see langword="null"/>.
 44        /// </exception>
 45        /// <exception cref="JsonException">
 46        /// <paramref name="returnType"/> is not compatible with the JSON.
 47        /// </exception>
 48        /// <exception cref="NotSupportedException">
 49        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 50        /// for <paramref name="returnType"/> or its serializable members.
 51        /// </exception>
 52        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 53        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 54        public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = nu
 055        {
 056            ArgumentNullException.ThrowIfNull(returnType);
 57
 058            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 059            ReadOnlySpan<byte> utf8Json = element.GetRawValue().Span;
 060            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 061        }
 62
 63        /// <summary>
 64        /// Converts the <see cref="JsonElement"/> representing a single JSON value into a <typeparamref name="TValue"/>
 65        /// </summary>
 66        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 67        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 68        /// <param name="element">The <see cref="JsonElement"/> to convert.</param>
 69        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 70        /// <exception cref="System.ArgumentNullException">
 71        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 72        /// </exception>
 73        /// <exception cref="JsonException">
 74        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 75        /// </exception>
 76        /// <exception cref="NotSupportedException">
 77        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 78        /// for <typeparamref name="TValue"/> or its serializable members.
 79        /// </exception>
 80        public static TValue? Deserialize<TValue>(this JsonElement element, JsonTypeInfo<TValue> jsonTypeInfo)
 081        {
 082            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 83
 084            jsonTypeInfo.EnsureConfigured();
 085            ReadOnlySpan<byte> utf8Json = element.GetRawValue().Span;
 086            return ReadFromSpan(utf8Json, jsonTypeInfo);
 087        }
 88
 89        /// <summary>
 90        /// Converts the <see cref="JsonElement"/> representing a single JSON value into an instance specified by the <p
 91        /// </summary>
 92        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 93        /// <param name="element">The <see cref="JsonElement"/> to convert.</param>
 94        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 95        /// <exception cref="System.ArgumentNullException">
 96        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 97        /// </exception>
 98        public static object? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo)
 099        {
 0100            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 101
 0102            jsonTypeInfo.EnsureConfigured();
 0103            ReadOnlySpan<byte> utf8Json = element.GetRawValue().Span;
 0104            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 0105        }
 106
 107        /// <summary>
 108        /// Converts the <see cref="JsonElement"/> representing a single JSON value into a <paramref name="returnType"/>
 109        /// </summary>
 110        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 111        /// <param name="element">The <see cref="JsonElement"/> to convert.</param>
 112        /// <param name="returnType">The type of the object to convert to and return.</param>
 113        /// <param name="context">A metadata provider for serializable types.</param>
 114        /// <exception cref="System.ArgumentNullException">
 115        /// <paramref name="returnType"/> is <see langword="null"/>.
 116        ///
 117        /// -or-
 118        ///
 119        /// <paramref name="context"/> is <see langword="null"/>.
 120        /// </exception>
 121        /// <exception cref="JsonException">
 122        /// The JSON is invalid.
 123        ///
 124        /// -or-
 125        ///
 126        /// <paramref name="returnType" /> is not compatible with the JSON.
 127        ///
 128        /// -or-
 129        ///
 130        /// There is remaining data in the string beyond a single JSON value.</exception>
 131        /// <exception cref="NotSupportedException">
 132        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 133        /// for <paramref name="returnType"/> or its serializable members.
 134        /// </exception>
 135        /// <exception cref="InvalidOperationException">
 136        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 137        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 138        /// </exception>
 139        public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerContext context)
 0140        {
 0141            ArgumentNullException.ThrowIfNull(returnType);
 0142            ArgumentNullException.ThrowIfNull(context);
 143
 0144            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0145            ReadOnlySpan<byte> utf8Json = element.GetRawValue().Span;
 0146            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 0147        }
 148    }
 149}
 150

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.Text.Json.Nodes;
 8using System.Text.Json.Serialization;
 9using System.Text.Json.Serialization.Metadata;
 10
 11namespace System.Text.Json
 12{
 13    public static partial class JsonSerializer
 14    {
 15        internal const string IdPropertyName = "$id";
 16        internal const string RefPropertyName = "$ref";
 17        internal const string TypePropertyName = "$type";
 18        internal const string ValuesPropertyName = "$values";
 19
 020        private static readonly byte[] s_idPropertyName = "$id"u8.ToArray();
 021        private static readonly byte[] s_refPropertyName = "$ref"u8.ToArray();
 022        private static readonly byte[] s_typePropertyName = "$type"u8.ToArray();
 023        private static readonly byte[] s_valuesPropertyName = "$values"u8.ToArray();
 24
 25        internal static bool TryReadMetadata(JsonConverter converter, JsonTypeInfo jsonTypeInfo, ref Utf8JsonReader read
 026        {
 027            Debug.Assert(state.Current.ObjectState == StackFrameObjectState.StartToken);
 028            Debug.Assert(state.Current.CanContainMetadata);
 29
 30            // Custom classifier branch: runs BEFORE normal metadata scanning.
 31            // When a TypeClassifier is configured, it replaces discriminator-based type resolution.
 032            PolymorphicTypeResolver? polymorphicResolver = jsonTypeInfo.PolymorphicTypeResolver;
 033            if (polymorphicResolver is not null && jsonTypeInfo.TypeClassifier is { } typeClassifier)
 034            {
 35                // Ensure the entire object is buffered (for streaming scenarios).
 036                if (!reader.IsFinalBlock)
 037                {
 038                    Utf8JsonReader bufferCheck = reader;
 039                    if (!bufferCheck.TrySkipPartial())
 040                    {
 041                        return false;
 42                    }
 043                }
 44
 45                // If reference handling is configured and the payload is a $ref-only object,
 46                // defer to the normal metadata loop so the reference resolver can return the
 47                // previously-deserialized instance instead of asking the classifier to identify
 48                // a type from a metadata-only payload that does not describe one.
 049                bool isRefOnlyPayload = false;
 050                if (state.ReferenceResolver is not null)
 051                {
 052                    Utf8JsonReader peek = reader;
 053                    if (peek.Read() &&
 054                        peek.TokenType == JsonTokenType.PropertyName &&
 055                        peek.GetUnescapedSpan().SequenceEqual(s_refPropertyName))
 056                    {
 057                        isRefOnlyPayload = true;
 058                    }
 059                }
 60
 061                if (!isRefOnlyPayload)
 062                {
 63                    // Classify using a struct copy; the original reader stays at the object start.
 064                    Utf8JsonReader classifierCopy = reader;
 065                    Type? resolvedType = typeClassifier(ref classifierCopy);
 66
 067                    if (resolvedType is null)
 068                    {
 069                        ThrowHelper.ThrowJsonException(SR.PolymorphicTypeClassifierReturnedNull);
 70                    }
 71
 072                    state.PolymorphicResolvedType = resolvedType;
 073                }
 074            }
 75
 76            Utf8JsonReader checkpoint;
 077            bool allowOutOfOrderMetadata = jsonTypeInfo.Options.AllowOutOfOrderMetadataProperties;
 078            bool isReadingAheadOfNonMetadataProperties = false;
 79
 080            if (allowOutOfOrderMetadata && !reader.IsFinalBlock)
 081            {
 82                // When reading ahead for metadata properties, we need to make sure
 83                // that the entire object has been buffered so that we can roll back
 84                // the reader state when the read-ahead has been completed.
 085                checkpoint = reader;
 086                if (!checkpoint.TrySkipPartial())
 087                {
 088                    return false;
 89                }
 090            }
 91            else
 092            {
 93                // Checkpointing not used in this mode.
 094                checkpoint = default;
 095            }
 96
 097            while (true)
 098            {
 099                if (state.Current.PropertyState == StackFramePropertyState.None)
 0100                {
 101                    // Read the property name.
 0102                    if (!reader.Read())
 0103                    {
 0104                        Debug.Assert(!allowOutOfOrderMetadata, "Object must have already been buffered in this mode.");
 0105                        return false;
 106                    }
 107
 0108                    state.Current.PropertyState = StackFramePropertyState.ReadName;
 0109                }
 110
 0111                if (state.Current.PropertyState < StackFramePropertyState.Name)
 0112                {
 0113                    if (reader.TokenType == JsonTokenType.EndObject)
 0114                    {
 115                        // Read the entire object while parsing for metadata.
 0116                        goto Done;
 117                    }
 118
 119                    // We just read a property. The only valid next tokens are EndObject and PropertyName.
 0120                    Debug.Assert(reader.TokenType == JsonTokenType.PropertyName);
 121
 0122                    if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Ref) != 0)
 0123                    {
 124                        // No properties whatsoever should follow a $ref property.
 0125                        ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reader.GetUne
 126                    }
 127
 0128                    ReadOnlySpan<byte> propertyName = reader.GetUnescapedSpan();
 0129                    switch (state.Current.LatestMetadataPropertyName = GetMetadataPropertyName(propertyName, jsonTypeInf
 130                    {
 131                        case MetadataPropertyName.Id:
 0132                            state.Current.JsonPropertyName = s_idPropertyName;
 133
 0134                            if (state.ReferenceResolver is null)
 0135                            {
 136                                // Found an $id property in a type that doesn't support reference preservation
 0137                                ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(propertyName, ref state);
 138                            }
 0139                            if ((state.Current.MetadataPropertyNames & (MetadataPropertyName.Id | MetadataPropertyName.R
 0140                            {
 141                                // No $id or $ref properties should precede $id properties.
 0142                                ThrowHelper.ThrowJsonException_MetadataIdCannotBeCombinedWithRef(propertyName, ref state
 143                            }
 0144                            if (!converter.CanHaveMetadata)
 0145                            {
 146                                // Should not be permitted unless the converter is capable of handling metadata.
 0147                                ThrowHelper.ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(converter
 148                            }
 149
 0150                            break;
 151
 152                        case MetadataPropertyName.Ref:
 0153                            state.Current.JsonPropertyName = s_refPropertyName;
 154
 0155                            if (state.ReferenceResolver is null)
 0156                            {
 157                                // Found a $ref property in a type that doesn't support reference preservation
 0158                                ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(propertyName, ref state);
 159                            }
 0160                            if (converter.IsValueType)
 0161                            {
 162                                // Should not be permitted if the converter is a struct.
 0163                                ThrowHelper.ThrowJsonException_MetadataInvalidReferenceToValueType(converter.Type!);
 164                            }
 0165                            if (state.Current.MetadataPropertyNames != 0 || isReadingAheadOfNonMetadataProperties)
 0166                            {
 167                                // No properties should precede a $ref property.
 0168                                ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(reade
 169                            }
 170
 0171                            break;
 172
 173                        case MetadataPropertyName.Type:
 0174                            state.Current.JsonPropertyName = jsonTypeInfo.PolymorphicTypeResolver?.CustomTypeDiscriminat
 175
 0176                            if (jsonTypeInfo.PolymorphicTypeResolver is null)
 0177                            {
 178                                // Found a $type property in a type that doesn't support polymorphism
 0179                                ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(propertyName, ref state);
 180                            }
 0181                            if (state.PolymorphicTypeDiscriminator is not null)
 0182                            {
 183                                // Found a duplicate $type property.
 0184                                ThrowHelper.ThrowJsonException_DuplicateMetadataProperty(state.Current.JsonPropertyName)
 185                            }
 186
 0187                            break;
 188
 189                        case MetadataPropertyName.Values:
 0190                            state.Current.JsonPropertyName = s_valuesPropertyName;
 191
 0192                            if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Values) != 0)
 0193                            {
 194                                // Found a duplicate $values property.
 0195                                ThrowHelper.ThrowJsonException_DuplicateMetadataProperty(s_valuesPropertyName);
 196                            }
 197
 0198                            if (isReadingAheadOfNonMetadataProperties)
 0199                            {
 200                                // Cannot combine a $values property with other non-metadata properties.
 0201                                ThrowHelper.ThrowJsonException_MetadataInvalidPropertyInArrayMetadata(ref state, jsonTyp
 202                            }
 203
 0204                            break;
 205
 206                        default:
 0207                            Debug.Assert(state.Current.LatestMetadataPropertyName == MetadataPropertyName.None);
 208
 209                            // Encountered a non-metadata property
 0210                            if (allowOutOfOrderMetadata)
 0211                            {
 0212                                if (!isReadingAheadOfNonMetadataProperties)
 0213                                {
 214                                    // This is the first non-metadata property, checkpoint the current reader state.
 0215                                    isReadingAheadOfNonMetadataProperties = true;
 0216                                    checkpoint = reader;
 0217                                }
 218
 0219                                if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Values) != 0)
 0220                                {
 221                                    // Cannot combine a $values property with other non-metadata properties.
 0222                                    ThrowHelper.ThrowJsonException_MetadataInvalidPropertyInArrayMetadata(ref state, jso
 223                                }
 224
 0225                                if (IsMetadataPropertyName(propertyName, resolver: null))
 0226                                {
 227                                    // properties starting with '$' are reserved for metadata
 0228                                    ThrowHelper.ThrowUnexpectedMetadataException(propertyName, ref reader, ref state);
 229                                }
 230
 0231                                break;
 232                            }
 233                            else
 0234                            {
 235                                // Exit immediately if no read-ahead is enabled.
 0236                                goto Done;
 237                            }
 238                    }
 239
 0240                    state.Current.PropertyState = StackFramePropertyState.Name;
 0241                }
 242
 0243                if (state.Current.PropertyState < StackFramePropertyState.ReadValue)
 0244                {
 245                    // Read the property value.
 0246                    if (!reader.Read())
 0247                    {
 0248                        Debug.Assert(!allowOutOfOrderMetadata, "Object must have already been buffered in this mode.");
 0249                        return false;
 250                    }
 251
 0252                    state.Current.PropertyState = StackFramePropertyState.ReadValue;
 0253                }
 254
 0255                Debug.Assert(state.Current.PropertyState == StackFramePropertyState.ReadValue);
 256
 0257                switch (state.Current.LatestMetadataPropertyName)
 258                {
 259                    case MetadataPropertyName.Id:
 0260                        if (reader.TokenType != JsonTokenType.String)
 0261                        {
 0262                            ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType);
 263                        }
 264
 0265                        if (state.ReferenceId is not null)
 0266                        {
 0267                            ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_
 268                        }
 269
 0270                        state.ReferenceId = reader.GetString();
 0271                        break;
 272
 273                    case MetadataPropertyName.Ref:
 0274                        if (reader.TokenType != JsonTokenType.String)
 0275                        {
 0276                            ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType);
 277                        }
 278
 0279                        if (state.ReferenceId is not null)
 0280                        {
 0281                            ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_
 282                        }
 283
 0284                        state.ReferenceId = reader.GetString();
 0285                        break;
 286
 287                    case MetadataPropertyName.Type:
 0288                        Debug.Assert(state.PolymorphicTypeDiscriminator is null);
 289
 0290                        switch (reader.TokenType)
 291                        {
 292                            case JsonTokenType.String:
 0293                                state.PolymorphicTypeDiscriminator = reader.GetString();
 0294                                break;
 295                            case JsonTokenType.Number:
 0296                                state.PolymorphicTypeDiscriminator = reader.GetInt32();
 0297                                break;
 298                            default:
 0299                                ThrowHelper.ThrowJsonException_MetadataValueWasNotString(reader.TokenType);
 300                                break;
 301                        }
 302
 0303                        break;
 304
 305                    case MetadataPropertyName.Values:
 306
 0307                        if (reader.TokenType != JsonTokenType.StartArray)
 0308                        {
 0309                            ThrowHelper.ThrowJsonException_MetadataValuesInvalidToken(reader.TokenType);
 310                        }
 311
 0312                        if (allowOutOfOrderMetadata)
 0313                        {
 314                            // The $values property contains the collection payload,
 315                            // checkpoint the current reader and continue the read-ahead.
 0316                            Debug.Assert(!isReadingAheadOfNonMetadataProperties, "must have already verified if non-meta
 0317                            isReadingAheadOfNonMetadataProperties = true;
 0318                            checkpoint = reader;
 0319                            reader.SkipWithVerify();
 0320                        }
 321                        else
 0322                        {
 0323                            state.Current.MetadataPropertyNames |= MetadataPropertyName.Values;
 0324                            state.Current.PropertyState = StackFramePropertyState.None;
 0325                            goto Done; // "$values" property contains the nested payload, exit the metadata reader now.
 326                        }
 327
 0328                        break;
 329
 330                    default:
 0331                        Debug.Assert(state.Current.LatestMetadataPropertyName == MetadataPropertyName.None);
 0332                        Debug.Assert(allowOutOfOrderMetadata, "should only be reached if reading ahead is required.");
 0333                        reader.SkipWithVerify();
 334
 0335                        break;
 336                }
 337
 0338                state.Current.MetadataPropertyNames |= state.Current.LatestMetadataPropertyName;
 0339                state.Current.PropertyState = StackFramePropertyState.None;
 0340                state.Current.JsonPropertyName = null;
 0341            }
 342
 0343        Done:
 0344            if (state.Current.MetadataPropertyNames is MetadataPropertyName.Values)
 0345            {
 346                // Cannot have a $values property unless there are other metadata properties.
 0347                ThrowHelper.ThrowJsonException_MetadataStandaloneValuesProperty(ref state, s_valuesPropertyName);
 348            }
 349
 0350            if (isReadingAheadOfNonMetadataProperties)
 0351            {
 352                // Roll back the reader state to the first non-metadata property.
 0353                reader = checkpoint;
 0354            }
 355
 0356            return true;
 0357        }
 358
 359        internal static bool IsMetadataPropertyName(ReadOnlySpan<byte> propertyName, PolymorphicTypeResolver? resolver)
 0360        {
 0361            return
 0362                (propertyName.Length > 0 && propertyName[0] == '$') ||
 0363                (resolver?.CustomTypeDiscriminatorPropertyNameUtf8?.AsSpan().SequenceEqual(propertyName) == true);
 0364        }
 365
 366        internal static MetadataPropertyName GetMetadataPropertyName(ReadOnlySpan<byte> propertyName, PolymorphicTypeRes
 0367        {
 0368            if (propertyName.Length > 0 && propertyName[0] == '$')
 0369            {
 0370                switch (propertyName.Length)
 371                {
 0372                    case 3 when propertyName.SequenceEqual("$id"u8):
 0373                        return MetadataPropertyName.Id;
 374
 0375                    case 4 when propertyName.SequenceEqual("$ref"u8):
 0376                        return MetadataPropertyName.Ref;
 377
 0378                    case 5 when resolver?.CustomTypeDiscriminatorPropertyNameUtf8 is null && propertyName.SequenceEqual(
 0379                        return MetadataPropertyName.Type;
 380
 0381                    case 7 when propertyName.SequenceEqual("$values"u8):
 0382                        return MetadataPropertyName.Values;
 383                }
 0384            }
 385
 0386            if (resolver?.CustomTypeDiscriminatorPropertyNameUtf8 is byte[] customTypeDiscriminator &&
 0387                propertyName.SequenceEqual(customTypeDiscriminator))
 0388            {
 0389                return MetadataPropertyName.Type;
 390            }
 391
 0392            return MetadataPropertyName.None;
 0393        }
 394
 395        internal static bool TryHandleReferenceFromJsonElement(
 396            ref Utf8JsonReader reader,
 397            scoped ref ReadStack state,
 398            JsonElement element,
 399            [NotNullWhen(true)] out object? referenceValue)
 0400        {
 0401            bool refMetadataFound = false;
 0402            referenceValue = default;
 403
 0404            if (element.ValueKind == JsonValueKind.Object)
 0405            {
 0406                int propertyCount = 0;
 0407                foreach (JsonProperty property in element.EnumerateObject())
 0408                {
 0409                    propertyCount++;
 0410                    if (refMetadataFound)
 0411                    {
 412                        // There are more properties in an object with $ref.
 0413                        ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
 414                    }
 0415                    else if (property.EscapedNameEquals(s_idPropertyName))
 0416                    {
 0417                        if (state.ReferenceId is not null)
 0418                        {
 0419                            ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_
 420                        }
 421
 0422                        if (property.Value.ValueKind != JsonValueKind.String)
 0423                        {
 0424                            ThrowHelper.ThrowJsonException_MetadataValueWasNotString(property.Value.ValueKind);
 425                        }
 426
 0427                        object boxedElement = element;
 0428                        state.ReferenceResolver.AddReference(property.Value.GetString()!, boxedElement);
 0429                        referenceValue = boxedElement;
 0430                        return true;
 431                    }
 0432                    else if (property.EscapedNameEquals(s_refPropertyName))
 0433                    {
 0434                        if (state.ReferenceId is not null)
 0435                        {
 0436                            ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_
 437                        }
 438
 0439                        if (propertyCount > 1)
 0440                        {
 441                            // $ref was found but there were other properties before.
 0442                            ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
 443                        }
 444
 0445                        if (property.Value.ValueKind != JsonValueKind.String)
 0446                        {
 0447                            ThrowHelper.ThrowJsonException_MetadataValueWasNotString(property.Value.ValueKind);
 448                        }
 449
 0450                        referenceValue = state.ReferenceResolver.ResolveReference(property.Value.GetString()!);
 0451                        refMetadataFound = true;
 0452                    }
 0453                }
 0454            }
 455
 0456            return refMetadataFound;
 0457        }
 458
 459        internal static bool TryHandleReferenceFromJsonNode(
 460            ref Utf8JsonReader reader,
 461            scoped ref ReadStack state,
 462            JsonNode? jsonNode,
 463            [NotNullWhen(true)] out object? referenceValue)
 0464        {
 0465            bool refMetadataFound = false;
 0466            referenceValue = default;
 467
 0468            if (jsonNode is JsonObject jsonObject)
 0469            {
 0470                int propertyCount = 0;
 0471                foreach (KeyValuePair<string, JsonNode?> property in jsonObject)
 0472                {
 0473                    propertyCount++;
 0474                    if (refMetadataFound)
 0475                    {
 476                        // There are more properties in an object with $ref.
 0477                        ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
 478                    }
 0479                    else if (property.Key == "$id")
 0480                    {
 0481                        if (state.ReferenceId is not null)
 0482                        {
 0483                            ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_
 484                        }
 485
 0486                        string referenceId = ReadAsStringMetadataValue(property.Value);
 0487                        state.ReferenceResolver.AddReference(referenceId, jsonNode);
 0488                        referenceValue = jsonNode;
 0489                        return true;
 490                    }
 0491                    else if (property.Key == "$ref")
 0492                    {
 0493                        if (state.ReferenceId is not null)
 0494                        {
 0495                            ThrowHelper.ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotSupported(s_
 496                        }
 497
 0498                        if (propertyCount > 1)
 0499                        {
 500                            // $ref was found but there were other properties before.
 0501                            ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
 502                        }
 503
 0504                        string referenceId = ReadAsStringMetadataValue(property.Value);
 0505                        referenceValue = state.ReferenceResolver.ResolveReference(referenceId);
 0506                        refMetadataFound = true;
 0507                    }
 508
 509                    static string ReadAsStringMetadataValue(JsonNode? jsonNode)
 0510                    {
 0511                        if (jsonNode is JsonValue jsonValue &&
 0512                            jsonValue.TryGetValue(out string? value) &&
 0513                            value is not null)
 0514                        {
 0515                            return value;
 516                        }
 517
 0518                        JsonValueKind metadataValueKind = jsonNode?.GetValueKind() ?? JsonValueKind.Null;
 0519                        Debug.Assert(metadataValueKind != JsonValueKind.Undefined);
 0520                        ThrowHelper.ThrowJsonException_MetadataValueWasNotString(metadataValueKind);
 521                        return null!;
 0522                    }
 0523                }
 0524            }
 525
 0526            return refMetadataFound;
 0527        }
 528
 529        internal static void ValidateMetadataForObjectConverter(ref ReadStack state)
 0530        {
 0531            if ((state.Current.MetadataPropertyNames & MetadataPropertyName.Values) != 0)
 0532            {
 533                // Object converters do not support $values metadata.
 0534                ThrowHelper.ThrowJsonException_MetadataUnexpectedProperty(s_valuesPropertyName, ref state);
 535            }
 0536        }
 537
 538        internal static void ValidateMetadataForArrayConverter(JsonConverter converter, ref Utf8JsonReader reader, scope
 0539        {
 0540            switch (reader.TokenType)
 541            {
 542                case JsonTokenType.StartArray:
 0543                    Debug.Assert(state.Current.MetadataPropertyNames is MetadataPropertyName.None || state.Current.Metad
 0544                    break;
 545
 546                case JsonTokenType.EndObject:
 0547                    if (state.Current.MetadataPropertyNames != MetadataPropertyName.Ref)
 0548                    {
 549                        // Read the entire JSON object while parsing for metadata: for collection converters this is onl
 0550                        ThrowHelper.ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref state, converter.Type!);
 551                    }
 0552                    break;
 553
 554                default:
 0555                    Debug.Assert(reader.TokenType == JsonTokenType.PropertyName);
 556                    // Do not tolerate non-metadata properties in collection converters.
 0557                    ThrowHelper.ThrowJsonException_MetadataInvalidPropertyInArrayMetadata(ref state, converter.Type!, re
 558                    break;
 559            }
 0560        }
 561
 562        internal static T ResolveReferenceId<T>(ref ReadStack state)
 0563        {
 0564            Debug.Assert(!typeof(T).IsValueType);
 0565            Debug.Assert(state.ReferenceId is not null);
 566
 0567            string referenceId = state.ReferenceId;
 0568            object value = state.ReferenceResolver.ResolveReference(referenceId);
 0569            state.ReferenceId = null;
 570
 571            try
 0572            {
 0573                return (T)value;
 574            }
 0575            catch (InvalidCastException)
 0576            {
 0577                ThrowHelper.ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(
 0578                    referenceId, value.GetType(), typeof(T));
 579                return default!;
 580            }
 0581        }
 582    }
 583}
 584

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Runtime.CompilerServices;
 7using System.Text.Json.Reflection;
 8using System.Text.Json.Serialization;
 9using System.Text.Json.Serialization.Metadata;
 10
 11namespace System.Text.Json
 12{
 13    public static partial class JsonSerializer
 14    {
 15        /// <summary>
 16        /// Lookup the property given its name (obtained from the reader) and return it.
 17        /// Also sets state.Current.JsonPropertyInfo to a non-null value.
 18        /// </summary>
 19        internal static JsonPropertyInfo LookupProperty(
 20            object? obj,
 21            ReadOnlySpan<byte> unescapedPropertyName,
 22            ref ReadStack state,
 23            JsonSerializerOptions options,
 24            out bool useExtensionProperty,
 25            bool createExtensionProperty = true)
 026        {
 027            JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;
 028            useExtensionProperty = false;
 29
 030            JsonPropertyInfo? jsonPropertyInfo = jsonTypeInfo.GetProperty(
 031                unescapedPropertyName,
 032                ref state.Current,
 033                out byte[] utf8PropertyName);
 34
 35            // Increment PropertyIndex so GetProperty() checks the next property first when called again.
 036            state.Current.PropertyIndex++;
 37
 38            // For case insensitive and missing property support of JsonPath, remember the value on the temporary stack.
 039            state.Current.JsonPropertyName = utf8PropertyName;
 40
 41            // Handle missing properties
 042            if (jsonPropertyInfo is null)
 043            {
 044                if (jsonTypeInfo.EffectiveUnmappedMemberHandling is JsonUnmappedMemberHandling.Disallow)
 045                {
 046                    Debug.Assert(jsonTypeInfo.ExtensionDataProperty is null, "jsonTypeInfo.Configure() should have caugh
 047                    string stringPropertyName = Encoding.UTF8.GetString(unescapedPropertyName);
 048                    ThrowHelper.ThrowJsonException_UnmappedJsonProperty(jsonTypeInfo.Type, stringPropertyName);
 49                }
 50
 51                // Determine if we should use the extension property.
 052                if (jsonTypeInfo.ExtensionDataProperty is JsonPropertyInfo { HasGetter: true, HasSetter: true } dataExtP
 053                {
 054                    state.Current.JsonPropertyNameAsString = Encoding.UTF8.GetString(unescapedPropertyName);
 55
 056                    if (createExtensionProperty)
 057                    {
 058                        Debug.Assert(obj is not null, "obj is null");
 059                        CreateExtensionDataProperty(obj, dataExtProperty, options);
 060                    }
 61
 062                    jsonPropertyInfo = dataExtProperty;
 063                    useExtensionProperty = true;
 064                }
 65                else
 066                {
 67                    // Populate with a placeholder value required by JsonPath calculations
 068                    jsonPropertyInfo = JsonPropertyInfo.s_missingProperty;
 069                }
 070            }
 71
 072            state.Current.JsonPropertyInfo = jsonPropertyInfo;
 073            state.Current.NumberHandling = jsonPropertyInfo.EffectiveNumberHandling;
 074            return jsonPropertyInfo;
 075        }
 76
 77        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 78        internal static ReadOnlySpan<byte> GetPropertyName(
 79            scoped ref ReadStack state,
 80            ref Utf8JsonReader reader,
 81            JsonSerializerOptions options,
 82            out bool isAlreadyReadMetadataProperty)
 083        {
 084            ReadOnlySpan<byte> propertyName = reader.GetUnescapedSpan();
 085            isAlreadyReadMetadataProperty = false;
 86
 087            if (state.Current.CanContainMetadata)
 088            {
 089                if (IsMetadataPropertyName(propertyName, state.Current.BaseJsonTypeInfo.PolymorphicTypeResolver))
 090                {
 091                    if (options.AllowOutOfOrderMetadataProperties)
 092                    {
 093                        isAlreadyReadMetadataProperty = true;
 094                    }
 95                    else
 096                    {
 097                        ThrowHelper.ThrowUnexpectedMetadataException(propertyName, ref reader, ref state);
 98                    }
 099                }
 0100            }
 101
 0102            return propertyName;
 0103        }
 104
 105        internal static void CreateExtensionDataProperty(
 106            object obj,
 107            JsonPropertyInfo jsonPropertyInfo,
 108            JsonSerializerOptions options)
 0109        {
 0110            Debug.Assert(jsonPropertyInfo is not null);
 111
 0112            object? extensionData = jsonPropertyInfo.GetValueAsObject(obj);
 113
 114            // For IReadOnlyDictionary, if there's an existing non-null instance, we need to create a new mutable
 115            // Dictionary seeded with the existing contents so we can add the deserialized extension data to it.
 0116            bool isReadOnlyDictionary = jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary<string, object>) ||
 0117                                        jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary<string, JsonElement>
 118
 0119            if (extensionData is null || (isReadOnlyDictionary && extensionData is not null))
 0120            {
 121                // Create the appropriate dictionary type. We already verified the types.
 122#if DEBUG
 0123                Type? underlyingIDictionaryType = jsonPropertyInfo.PropertyType.GetCompatibleGenericInterface(typeof(IDi
 0124                    ?? jsonPropertyInfo.PropertyType.GetCompatibleGenericInterface(typeof(IReadOnlyDictionary<,>));
 0125                Debug.Assert(underlyingIDictionaryType is not null);
 0126                Type[] genericArgs = underlyingIDictionaryType.GetGenericArguments();
 127
 0128                Debug.Assert(underlyingIDictionaryType.IsGenericType);
 0129                Debug.Assert(genericArgs.Length == 2);
 0130                Debug.Assert(genericArgs[0].UnderlyingSystemType == typeof(string));
 0131                Debug.Assert(
 0132                    genericArgs[1].UnderlyingSystemType == typeof(object) ||
 0133                    genericArgs[1].UnderlyingSystemType == typeof(JsonElement) ||
 0134                    genericArgs[1].UnderlyingSystemType == typeof(Nodes.JsonNode));
 135#endif
 136
 0137                Func<object>? createObjectForExtensionDataProp = jsonPropertyInfo.JsonTypeInfo.CreateObject
 0138                    ?? jsonPropertyInfo.JsonTypeInfo.CreateObjectForExtensionDataProperty;
 139
 0140                if (createObjectForExtensionDataProp is null)
 0141                {
 142                    // Avoid a reference to the JsonNode type for trimming
 0143                    if (jsonPropertyInfo.PropertyType.FullName == JsonTypeInfo.JsonObjectTypeName)
 0144                    {
 0145                        ThrowHelper.ThrowInvalidOperationException_NodeJsonObjectCustomConverterNotAllowedOnExtensionPro
 146                    }
 147                    // For IReadOnlyDictionary<string, object> or IReadOnlyDictionary<string, JsonElement> interface typ
 148                    // create a Dictionary<TKey, TValue> instance seeded with any existing contents.
 0149                    else if (jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary<string, object>))
 0150                    {
 0151                        if (extensionData is not null)
 0152                        {
 0153                            var existing = (IReadOnlyDictionary<string, object>)extensionData;
 0154                            var newDict = new Dictionary<string, object>();
 0155                            foreach (KeyValuePair<string, object> kvp in existing)
 0156                            {
 0157                                newDict[kvp.Key] = kvp.Value;
 0158                            }
 0159                            extensionData = newDict;
 0160                        }
 161                        else
 0162                        {
 0163                            extensionData = new Dictionary<string, object>();
 0164                        }
 0165                        Debug.Assert(jsonPropertyInfo.Set is not null);
 0166                        jsonPropertyInfo.Set(obj, extensionData);
 0167                        return;
 168                    }
 0169                    else if (jsonPropertyInfo.PropertyType == typeof(IReadOnlyDictionary<string, JsonElement>))
 0170                    {
 0171                        if (extensionData is not null)
 0172                        {
 0173                            var existing = (IReadOnlyDictionary<string, JsonElement>)extensionData;
 0174                            var newDict = new Dictionary<string, JsonElement>();
 0175                            foreach (KeyValuePair<string, JsonElement> kvp in existing)
 0176                            {
 0177                                newDict[kvp.Key] = kvp.Value;
 0178                            }
 0179                            extensionData = newDict;
 0180                        }
 181                        else
 0182                        {
 0183                            extensionData = new Dictionary<string, JsonElement>();
 0184                        }
 0185                        Debug.Assert(jsonPropertyInfo.Set is not null);
 0186                        jsonPropertyInfo.Set(obj, extensionData);
 0187                        return;
 188                    }
 189                    else
 0190                    {
 0191                        ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(jsonPropertyInfo.PropertyType);
 192                    }
 193                }
 194
 0195                extensionData = createObjectForExtensionDataProp();
 0196                Debug.Assert(jsonPropertyInfo.Set is not null);
 0197                jsonPropertyInfo.Set(obj, extensionData);
 0198            }
 199
 200            // We don't add the value to the dictionary here because we need to support the read-ahead functionality for
 0201        }
 202    }
 203}
 204

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Nodes;
 7using System.Text.Json.Serialization;
 8using System.Text.Json.Serialization.Metadata;
 9
 10namespace System.Text.Json
 11{
 12    public static partial class JsonSerializer
 13    {
 14        /// <summary>
 15        /// Converts the <see cref="JsonNode"/> representing a single JSON value into a <typeparamref name="TValue"/>.
 16        /// </summary>
 17        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 18        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 19        /// <param name="node">The <see cref="JsonNode"/> to convert.</param>
 20        /// <param name="options">Options to control the behavior during parsing.</param>
 21        /// <exception cref="JsonException">
 22        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 23        /// </exception>
 24        /// <exception cref="NotSupportedException">
 25        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 26        /// for <typeparamref name="TValue"/> or its serializable members.
 27        /// </exception>
 28        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 29        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 30        public static TValue? Deserialize<TValue>(this JsonNode? node, JsonSerializerOptions? options = null)
 031        {
 032            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 033            return ReadFromNode(node, jsonTypeInfo);
 034        }
 35
 36        /// <summary>
 37        /// Converts the <see cref="JsonNode"/> representing a single JSON value into a <paramref name="returnType"/>.
 38        /// </summary>
 39        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 40        /// <param name="node">The <see cref="JsonNode"/> to convert.</param>
 41        /// <param name="returnType">The type of the object to convert to and return.</param>
 42        /// <param name="options">Options to control the behavior during parsing.</param>
 43        /// <exception cref="JsonException">
 44        /// <paramref name="returnType"/> is not compatible with the JSON.
 45        /// </exception>
 46        /// <exception cref="NotSupportedException">
 47        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 48        /// for <paramref name="returnType"/> or its serializable members.
 49        /// </exception>
 50        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 51        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 52        public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerOptions? options = null)
 053        {
 054            ArgumentNullException.ThrowIfNull(returnType);
 55
 056            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 057            return ReadFromNodeAsObject(node, jsonTypeInfo);
 058        }
 59
 60        /// <summary>
 61        /// Converts the <see cref="JsonNode"/> representing a single JSON value into a <typeparamref name="TValue"/>.
 62        /// </summary>
 63        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 64        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 65        /// <param name="node">The <see cref="JsonNode"/> to convert.</param>
 66        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 67        /// <exception cref="System.ArgumentNullException">
 68        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 69        /// </exception>
 70        /// <exception cref="JsonException">
 71        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 72        /// </exception>
 73        public static TValue? Deserialize<TValue>(this JsonNode? node, JsonTypeInfo<TValue> jsonTypeInfo)
 074        {
 075            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 76
 077            jsonTypeInfo.EnsureConfigured();
 078            return ReadFromNode(node, jsonTypeInfo);
 079        }
 80
 81        /// <summary>
 82        /// Converts the <see cref="JsonNode"/> representing a single JSON value into an instance specified by the <para
 83        /// </summary>
 84        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 85        /// <param name="node">The <see cref="JsonNode"/> to convert.</param>
 86        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 87        /// <exception cref="System.ArgumentNullException">
 88        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 89        /// </exception>
 90        public static object? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo)
 091        {
 092            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 93
 094            jsonTypeInfo.EnsureConfigured();
 095            return ReadFromNodeAsObject(node, jsonTypeInfo);
 096        }
 97
 98        /// <summary>
 99        /// Converts the <see cref="JsonNode"/> representing a single JSON value into a <paramref name="returnType"/>.
 100        /// </summary>
 101        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 102        /// <param name="node">The <see cref="JsonNode"/> to convert.</param>
 103        /// <param name="returnType">The type of the object to convert to and return.</param>
 104        /// <param name="context">A metadata provider for serializable types.</param>
 105        /// <exception cref="System.ArgumentNullException">
 106        /// <paramref name="returnType"/> is <see langword="null"/>.
 107        ///
 108        /// -or-
 109        ///
 110        /// <paramref name="context"/> is <see langword="null"/>.
 111        /// </exception>
 112        /// <exception cref="JsonException">
 113        /// The JSON is invalid.
 114        ///
 115        /// -or-
 116        ///
 117        /// <paramref name="returnType" /> is not compatible with the JSON.
 118        ///
 119        /// -or-
 120        ///
 121        /// There is remaining data in the string beyond a single JSON value.</exception>
 122        /// <exception cref="NotSupportedException">
 123        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 124        /// for <paramref name="returnType"/> or its serializable members.
 125        /// </exception>
 126        /// <exception cref="InvalidOperationException">
 127        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 128        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 129        /// </exception>
 130        public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerContext context)
 0131        {
 0132            ArgumentNullException.ThrowIfNull(returnType);
 0133            ArgumentNullException.ThrowIfNull(context);
 134
 0135            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0136            return ReadFromNodeAsObject(node, jsonTypeInfo);
 0137        }
 138
 139        private static TValue? ReadFromNode<TValue>(JsonNode? node, JsonTypeInfo<TValue> jsonTypeInfo)
 0140        {
 0141            JsonSerializerOptions options = jsonTypeInfo.Options;
 142
 143            // For performance, share the same buffer across serialization and deserialization.
 0144            using var output = new PooledByteBufferWriter(options.DefaultBufferSize);
 0145            using (var writer = new Utf8JsonWriter(output, options.GetWriterOptions()))
 0146            {
 0147                if (node is null)
 0148                {
 0149                    writer.WriteNullValue();
 0150                }
 151                else
 0152                {
 0153                    node.WriteTo(writer, options);
 0154                }
 0155            }
 156
 0157            return ReadFromSpan(output.WrittenSpan, jsonTypeInfo);
 0158        }
 159
 160        private static object? ReadFromNodeAsObject(JsonNode? node, JsonTypeInfo jsonTypeInfo)
 0161        {
 0162            JsonSerializerOptions options = jsonTypeInfo.Options;
 163
 164            // For performance, share the same buffer across serialization and deserialization.
 0165            using var output = new PooledByteBufferWriter(options.DefaultBufferSize);
 0166            using (var writer = new Utf8JsonWriter(output, options.GetWriterOptions()))
 0167            {
 0168                if (node is null)
 0169                {
 0170                    writer.WriteNullValue();
 0171                }
 172                else
 0173                {
 0174                    node.WriteTo(writer, options);
 0175                }
 0176            }
 177
 0178            return ReadFromSpanAsObject(output.WrittenSpan, jsonTypeInfo);
 0179        }
 180    }
 181}
 182

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Pipe.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.IO.Pipelines;
 8using System.Runtime.CompilerServices;
 9using System.Text.Json.Serialization;
 10using System.Text.Json.Serialization.Metadata;
 11using System.Threading;
 12using System.Threading.Tasks;
 13
 14namespace System.Text.Json
 15{
 16    public static partial class JsonSerializer
 17    {
 18        /// <summary>
 19        /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 20        /// The PipeReader will be read to completion.
 21        /// </summary>
 22        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 23        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 24        /// <param name="utf8Json">JSON data to parse.</param>
 25        /// <param name="options">Options to control the behavior during reading.</param>
 26        /// <param name="cancellationToken">
 27        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 28        /// </param>
 29        /// <exception cref="System.ArgumentNullException">
 30        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 31        /// </exception>
 32        /// <exception cref="JsonException">
 33        /// The JSON is invalid,
 34        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 35        /// or when there is remaining data in the PipeReader.
 36        /// </exception>
 37        /// <exception cref="NotSupportedException">
 38        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 39        /// for <typeparamref name="TValue"/> or its serializable members.
 40        /// </exception>
 41        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 42        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 43        public static ValueTask<TValue?> DeserializeAsync<TValue>(
 44            PipeReader utf8Json,
 45            JsonSerializerOptions? options = null,
 46            CancellationToken cancellationToken = default)
 047        {
 048            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 49
 050            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 051            return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken);
 052        }
 53
 54        /// <summary>
 55        /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 56        /// The PipeReader will be read to completion.
 57        /// </summary>
 58        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 59        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 60        /// <param name="utf8Json">JSON data to parse.</param>
 61        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 62        /// <param name="cancellationToken">
 63        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 64        /// </param>
 65        /// <exception cref="System.ArgumentNullException">
 66        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 67        /// </exception>
 68        /// <exception cref="JsonException">
 69        /// The JSON is invalid,
 70        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 71        /// or when there is remaining data in the PipeReader.
 72        /// </exception>
 73        public static ValueTask<TValue?> DeserializeAsync<TValue>(
 74                PipeReader utf8Json,
 75                JsonTypeInfo<TValue> jsonTypeInfo,
 76                CancellationToken cancellationToken = default)
 077        {
 078            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 079            ArgumentNullException.ThrowIfNull(jsonTypeInfo, nameof(jsonTypeInfo));
 80
 081            jsonTypeInfo.EnsureConfigured();
 082            return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken);
 083        }
 84
 85        /// <summary>
 86        /// Reads the UTF-8 encoded text representing a single JSON value into an instance specified by the <paramref na
 87        /// The PipeReader will be read to completion.
 88        /// </summary>
 89        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 90        /// <param name="utf8Json">JSON data to parse.</param>
 91        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 92        /// <param name="cancellationToken">
 93        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 94        /// </param>
 95        /// <exception cref="System.ArgumentNullException">
 96        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 97        /// </exception>
 98        /// <exception cref="JsonException">
 99        /// The JSON is invalid,
 100        /// or when there is remaining data in the PipeReader.
 101        /// </exception>
 102        public static ValueTask<object?> DeserializeAsync(
 103                PipeReader utf8Json,
 104                JsonTypeInfo jsonTypeInfo,
 105                CancellationToken cancellationToken = default)
 0106        {
 0107            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 0108            ArgumentNullException.ThrowIfNull(jsonTypeInfo, nameof(jsonTypeInfo));
 109
 0110            jsonTypeInfo.EnsureConfigured();
 0111            return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken);
 0112        }
 113
 114        /// <summary>
 115        /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 116        /// The PipeReader will be read to completion.
 117        /// </summary>
 118        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 119        /// <param name="utf8Json">JSON data to parse.</param>
 120        /// <param name="returnType">The type of the object to convert to and return.</param>
 121        /// <param name="context">A metadata provider for serializable types.</param>
 122        /// <param name="cancellationToken">
 123        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 124        /// </param>
 125        /// <exception cref="System.ArgumentNullException">
 126        /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="
 127        /// </exception>
 128        /// <exception cref="JsonException">
 129        /// The JSON is invalid,
 130        /// the <paramref name="returnType"/> is not compatible with the JSON,
 131        /// or when there is remaining data in the PipeReader.
 132        /// </exception>
 133        /// <exception cref="NotSupportedException">
 134        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 135        /// for <paramref name="returnType"/> or its serializable members.
 136        /// </exception>
 137        /// <exception cref="InvalidOperationException">
 138        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
 139        /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
 140        /// </exception>
 141        public static ValueTask<object?> DeserializeAsync(
 142                PipeReader utf8Json,
 143                Type returnType,
 144                JsonSerializerContext context,
 145                CancellationToken cancellationToken = default)
 0146        {
 0147            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 0148            ArgumentNullException.ThrowIfNull(returnType, nameof(returnType));
 0149            ArgumentNullException.ThrowIfNull(context, nameof(context));
 150
 0151            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0152            return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken);
 0153        }
 154
 155        /// <summary>
 156        /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 157        /// The PipeReader will be read to completion.
 158        /// </summary>
 159        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 160        /// <param name="utf8Json">JSON data to parse.</param>
 161        /// <param name="returnType">The type of the object to convert to and return.</param>
 162        /// <param name="options">Options to control the behavior during reading.</param>
 163        /// <param name="cancellationToken">
 164        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 165        /// </param>
 166        /// <exception cref="System.ArgumentNullException">
 167        /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
 168        /// </exception>
 169        /// <exception cref="JsonException">
 170        /// The JSON is invalid,
 171        /// the <paramref name="returnType"/> is not compatible with the JSON,
 172        /// or when there is remaining data in the PipeReader.
 173        /// </exception>
 174        /// <exception cref="NotSupportedException">
 175        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 176        /// for <paramref name="returnType"/> or its serializable members.
 177        /// </exception>
 178        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 179        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 180        public static ValueTask<object?> DeserializeAsync(
 181               PipeReader utf8Json,
 182               Type returnType,
 183               JsonSerializerOptions? options = null,
 184               CancellationToken cancellationToken = default)
 0185        {
 0186            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 0187            ArgumentNullException.ThrowIfNull(returnType, nameof(returnType));
 188
 0189            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 0190            return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken);
 0191        }
 192
 193        /// <summary>
 194        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 195        /// that can be used to deserialize root-level JSON arrays in a streaming manner.
 196        /// </summary>
 197        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 198        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns>
 199        /// <param name="utf8Json">JSON data to parse.</param>
 200        /// <param name="options">Options to control the behavior during reading.</param>
 201        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 202        /// <exception cref="System.ArgumentNullException">
 203        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 204        /// </exception>
 205        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 206        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 207        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 208                PipeReader utf8Json,
 209                JsonSerializerOptions? options = null,
 210                CancellationToken cancellationToken = default)
 0211        {
 0212            return DeserializeAsyncEnumerable<TValue>(utf8Json, topLevelValues: false, options, cancellationToken);
 0213        }
 214
 215        /// <summary>
 216        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 217        /// that can be used to deserialize root-level JSON arrays in a streaming manner.
 218        /// </summary>
 219        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 220        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns>
 221        /// <param name="utf8Json">JSON data to parse.</param>
 222        /// <param name="jsonTypeInfo">Metadata about the element type to convert.</param>
 223        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 224        /// <exception cref="System.ArgumentNullException">
 225        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 226        /// </exception>
 227        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 228                PipeReader utf8Json,
 229                JsonTypeInfo<TValue> jsonTypeInfo,
 230                CancellationToken cancellationToken = default)
 0231        {
 0232            return DeserializeAsyncEnumerable(utf8Json, jsonTypeInfo, topLevelValues: false, cancellationToken);
 0233        }
 234
 235        /// <summary>
 236        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 237        /// that can be used to deserialize sequences of JSON values in a streaming manner.
 238        /// </summary>
 239        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 240        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON sequence.</returns>
 241        /// <param name="utf8Json">JSON data to parse.</param>
 242        /// <param name="jsonTypeInfo">Metadata about the element type to convert.</param>
 243        /// <param name="topLevelValues"><see langword="true"/> to deserialize from a sequence of top-level JSON values
 244        /// (for example, a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"
 245        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 246        /// <exception cref="System.ArgumentNullException">
 247        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 248        /// </exception>
 249        /// <remarks>
 250        /// When <paramref name="topLevelValues"/> is set to <see langword="true" />, treats the PipeReader as a sequenc
 251        /// whitespace separated top-level JSON values and attempts to deserialize each value into <typeparamref name="T
 252        /// This is a superset of the <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> format and can be used
 253        /// When <paramref name="topLevelValues"/> is set to <see langword="false" />, treats the PipeReader as a JSON a
 254        /// attempts to deserialize each element into <typeparamref name="TValue"/>.
 255        /// </remarks>
 256        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 257            PipeReader utf8Json,
 258            JsonTypeInfo<TValue> jsonTypeInfo,
 259            bool topLevelValues,
 260            CancellationToken cancellationToken = default)
 0261        {
 0262            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 0263            ArgumentNullException.ThrowIfNull(jsonTypeInfo, nameof(jsonTypeInfo));
 264
 0265            jsonTypeInfo.EnsureConfigured();
 0266            return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, topLevelValues, cancellationToken);
 0267        }
 268
 269        /// <summary>
 270        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 271        /// that can be used to deserialize sequences of JSON values in a streaming manner.
 272        /// </summary>
 273        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 274        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON sequence.</returns>
 275        /// <param name="utf8Json">JSON data to parse.</param>
 276        /// <param name="topLevelValues"><see langword="true"/> to deserialize from a sequence of top-level JSON values
 277        /// (for example, a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"
 278        /// <param name="options">Options to control the behavior during reading.</param>
 279        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 280        /// <exception cref="System.ArgumentNullException">
 281        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 282        /// </exception>
 283        /// <remarks>
 284        /// When <paramref name="topLevelValues"/> is set to <see langword="true" />, treats the PipeReader as a sequenc
 285        /// whitespace separated top-level JSON values and attempts to deserialize each value into <typeparamref name="T
 286        /// This is a superset of the <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> format and can be used
 287        /// When <paramref name="topLevelValues"/> is set to <see langword="false" />, treats the PipeReader as a JSON a
 288        /// attempts to deserialize each element into <typeparamref name="TValue"/>.
 289        /// </remarks>
 290        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 291        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 292        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 293            PipeReader utf8Json,
 294            bool topLevelValues,
 295            JsonSerializerOptions? options = null,
 296            CancellationToken cancellationToken = default)
 0297        {
 0298            ArgumentNullException.ThrowIfNull(utf8Json, nameof(utf8Json));
 299
 0300            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 0301            return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, topLevelValues, cancellationToken);
 0302        }
 303
 304        private static IAsyncEnumerable<T?> DeserializeAsyncEnumerableCore<T>(
 305            PipeReader utf8Json,
 306            JsonTypeInfo<T> jsonTypeInfo,
 307            bool topLevelValues,
 308            CancellationToken cancellationToken)
 0309        {
 0310            Debug.Assert(jsonTypeInfo.IsConfigured);
 311
 312            JsonTypeInfo<List<T?>> listTypeInfo;
 0313            JsonReaderOptions readerOptions = jsonTypeInfo.Options.GetReaderOptions();
 0314            if (topLevelValues)
 0315            {
 0316                listTypeInfo = GetOrAddListTypeInfoForRootLevelValueMode(jsonTypeInfo);
 0317                readerOptions.AllowMultipleValues = true;
 0318            }
 319            else
 0320            {
 0321                listTypeInfo = GetOrAddListTypeInfoForArrayMode(jsonTypeInfo);
 0322            }
 323
 0324            return CreateAsyncEnumerableFromArray(utf8Json, listTypeInfo, readerOptions, cancellationToken);
 325
 326            static async IAsyncEnumerable<T?> CreateAsyncEnumerableFromArray(
 327                PipeReader utf8Json,
 328                JsonTypeInfo<List<T?>> listTypeInfo,
 329                JsonReaderOptions readerOptions,
 330                [EnumeratorCancellation] CancellationToken cancellationToken)
 0331            {
 0332                Debug.Assert(listTypeInfo.IsConfigured);
 333
 0334                ReadStack readStack = default;
 0335                readStack.Initialize(listTypeInfo, supportContinuation: true);
 0336                JsonReaderState jsonReaderState = new(readerOptions);
 0337                PipeReadBufferState bufferState = new(utf8Json);
 338
 339                try
 0340                {
 341                    bool success;
 342                    do
 0343                    {
 0344                        bufferState = await bufferState.ReadAsync(utf8Json, cancellationToken, fillBuffer: false).Config
 0345                        success = listTypeInfo.ContinueDeserialize<PipeReadBufferState, PipeReader>(
 0346                            ref bufferState,
 0347                            ref jsonReaderState,
 0348                            ref readStack,
 0349                            out List<T?>? _);
 350
 0351                        if (readStack.Current.ReturnValue is { } returnValue)
 0352                        {
 0353                            var list = (List<T?>)returnValue;
 0354                            foreach (T? item in list)
 0355                            {
 0356                                yield return item;
 0357                            }
 358
 0359                            list.Clear();
 0360                        }
 0361                    } while (!success);
 0362                }
 363                finally
 0364                {
 0365                    bufferState.Dispose();
 0366                }
 0367            }
 0368        }
 369    }
 370}
 371

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Serialization;
 7using System.Text.Json.Serialization.Metadata;
 8
 9namespace System.Text.Json
 10{
 11    public static partial class JsonSerializer
 12    {
 13        /// <summary>
 14        /// Parses the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 15        /// </summary>
 16        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 17        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 18        /// <param name="utf8Json">JSON text to parse.</param>
 19        /// <param name="options">Options to control the behavior during parsing.</param>
 20        /// <exception cref="JsonException">
 21        /// The JSON is invalid,
 22        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 23        /// or when there is remaining data in the Stream.
 24        /// </exception>
 25        /// <exception cref="NotSupportedException">
 26        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 27        /// for <typeparamref name="TValue"/> or its serializable members.
 28        /// </exception>
 29        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 30        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 31        public static TValue? Deserialize<TValue>(ReadOnlySpan<byte> utf8Json, JsonSerializerOptions? options = null)
 032        {
 033            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 034            return ReadFromSpan(utf8Json, jsonTypeInfo);
 035        }
 36
 37        /// <summary>
 38        /// Parses the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 39        /// </summary>
 40        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 41        /// <param name="utf8Json">JSON text to parse.</param>
 42        /// <param name="returnType">The type of the object to convert to and return.</param>
 43        /// <param name="options">Options to control the behavior during parsing.</param>
 44        /// <exception cref="System.ArgumentNullException">
 45        /// <paramref name="returnType"/> is <see langword="null"/>.
 46        /// </exception>
 47        /// <exception cref="JsonException">
 48        /// The JSON is invalid,
 49        /// <paramref name="returnType"/> is not compatible with the JSON,
 50        /// or when there is remaining data in the Stream.
 51        /// </exception>
 52        /// <exception cref="NotSupportedException">
 53        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 54        /// for <paramref name="returnType"/> or its serializable members.
 55        /// </exception>
 56        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 57        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 58        public static object? Deserialize(ReadOnlySpan<byte> utf8Json, Type returnType, JsonSerializerOptions? options =
 059        {
 060            ArgumentNullException.ThrowIfNull(returnType);
 61
 062            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 063            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 064        }
 65
 66        /// <summary>
 67        /// Parses the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 68        /// </summary>
 69        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 70        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 71        /// <param name="utf8Json">JSON text to parse.</param>
 72        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 73        /// <exception cref="JsonException">
 74        /// The JSON is invalid,
 75        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 76        /// or when there is remaining data in the buffer.
 77        /// </exception>
 78        public static TValue? Deserialize<TValue>(ReadOnlySpan<byte> utf8Json, JsonTypeInfo<TValue> jsonTypeInfo)
 079        {
 080            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 81
 082            jsonTypeInfo.EnsureConfigured();
 083            return ReadFromSpan(utf8Json, jsonTypeInfo);
 084        }
 85
 86        /// <summary>
 87        /// Parses the UTF-8 encoded text representing a single JSON value into an instance specified by the <paramref n
 88        /// </summary>
 89        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 90        /// <param name="utf8Json">JSON text to parse.</param>
 91        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 92        /// <exception cref="JsonException">
 93        /// The JSON is invalid,
 94        /// or there is remaining data in the buffer.
 95        /// </exception>
 96        public static object? Deserialize(ReadOnlySpan<byte> utf8Json, JsonTypeInfo jsonTypeInfo)
 097        {
 098            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 99
 0100            jsonTypeInfo.EnsureConfigured();
 0101            return ReadFromSpanAsObject(utf8Json, jsonTypeInfo);
 0102        }
 103
 104        /// <summary>
 105        /// Parses the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 106        /// </summary>
 107        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 108        /// <param name="utf8Json">JSON text to parse.</param>
 109        /// <param name="returnType">The type of the object to convert to and return.</param>
 110        /// <param name="context">A metadata provider for serializable types.</param>
 111        /// <exception cref="System.ArgumentNullException">
 112        /// <paramref name="returnType"/> is <see langword="null"/>.
 113        /// </exception>
 114        /// <exception cref="JsonException">
 115        /// The JSON is invalid,
 116        /// <paramref name="returnType"/> is not compatible with the JSON,
 117        /// or when there is remaining data in the Stream.
 118        /// </exception>
 119        /// <exception cref="NotSupportedException">
 120        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 121        /// for <paramref name="returnType"/> or its serializable members.
 122        /// </exception>
 123        /// <exception cref="InvalidOperationException">
 124        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
 125        /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
 126        /// </exception>
 127        public static object? Deserialize(ReadOnlySpan<byte> utf8Json, Type returnType, JsonSerializerContext context)
 0128        {
 0129            ArgumentNullException.ThrowIfNull(returnType);
 0130            ArgumentNullException.ThrowIfNull(context);
 131
 0132            return ReadFromSpanAsObject(utf8Json, GetTypeInfo(context, returnType));
 0133        }
 134
 135        private static TValue? ReadFromSpan<TValue>(ReadOnlySpan<byte> utf8Json, JsonTypeInfo<TValue> jsonTypeInfo, int?
 0136        {
 0137            Debug.Assert(jsonTypeInfo.IsConfigured);
 138
 0139            var readerState = new JsonReaderState(jsonTypeInfo.Options.GetReaderOptions());
 0140            var reader = new Utf8JsonReader(utf8Json, isFinalBlock: true, readerState);
 141
 0142            ReadStack state = default;
 0143            state.Initialize(jsonTypeInfo);
 144
 0145            TValue? value = jsonTypeInfo.Deserialize(ref reader, ref state);
 146
 147            // The reader should have thrown if we have remaining bytes, unless AllowMultipleValues is true.
 0148            Debug.Assert(reader.BytesConsumed == (actualByteCount ?? utf8Json.Length) || reader.CurrentState.Options.All
 0149            return value;
 0150        }
 151
 152        private static object? ReadFromSpanAsObject(ReadOnlySpan<byte> utf8Json, JsonTypeInfo jsonTypeInfo, int? actualB
 0153        {
 0154            Debug.Assert(jsonTypeInfo.IsConfigured);
 155
 0156            var readerState = new JsonReaderState(jsonTypeInfo.Options.GetReaderOptions());
 0157            var reader = new Utf8JsonReader(utf8Json, isFinalBlock: true, readerState);
 158
 0159            ReadStack state = default;
 0160            state.Initialize(jsonTypeInfo);
 161
 0162            object? value = jsonTypeInfo.DeserializeAsObject(ref reader, ref state);
 163
 164            // The reader should have thrown if we have remaining bytes, unless AllowMultipleValues is true.
 0165            Debug.Assert(reader.BytesConsumed == (actualByteCount ?? utf8Json.Length) || reader.CurrentState.Options.All
 0166            return value;
 0167        }
 168    }
 169}
 170

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.IO;
 8using System.Runtime.CompilerServices;
 9using System.Text.Json.Serialization;
 10using System.Text.Json.Serialization.Metadata;
 11using System.Threading;
 12using System.Threading.Tasks;
 13
 14namespace System.Text.Json
 15{
 16    public static partial class JsonSerializer
 17    {
 18        /// <summary>
 19        /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 20        /// The Stream will be read to completion.
 21        /// </summary>
 22        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 23        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 24        /// <param name="utf8Json">JSON data to parse.</param>
 25        /// <param name="options">Options to control the behavior during reading.</param>
 26        /// <param name="cancellationToken">
 27        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 28        /// </param>
 29        /// <exception cref="System.ArgumentNullException">
 30        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 31        /// </exception>
 32        /// <exception cref="JsonException">
 33        /// The JSON is invalid,
 34        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 35        /// or when there is remaining data in the Stream.
 36        /// </exception>
 37        /// <exception cref="NotSupportedException">
 38        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 39        /// for <typeparamref name="TValue"/> or its serializable members.
 40        /// </exception>
 41        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 42        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 43        public static ValueTask<TValue?> DeserializeAsync<TValue>(
 44            Stream utf8Json,
 45            JsonSerializerOptions? options = null,
 46            CancellationToken cancellationToken = default)
 047        {
 048            ArgumentNullException.ThrowIfNull(utf8Json);
 49
 050            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 051            return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken);
 052        }
 53
 54        /// <summary>
 55        /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 56        /// The Stream will be read to completion.
 57        /// </summary>
 58        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 59        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 60        /// <param name="utf8Json">JSON data to parse.</param>
 61        /// <param name="options">Options to control the behavior during reading.</param>
 62        /// <exception cref="System.ArgumentNullException">
 63        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 64        /// </exception>
 65        /// <exception cref="JsonException">
 66        /// The JSON is invalid,
 67        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 68        /// or when there is remaining data in the Stream.
 69        /// </exception>
 70        /// <exception cref="NotSupportedException">
 71        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 72        /// for <typeparamref name="TValue"/> or its serializable members.
 73        /// </exception>
 74        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 75        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 76        public static TValue? Deserialize<TValue>(
 77            Stream utf8Json,
 78            JsonSerializerOptions? options = null)
 079        {
 080            ArgumentNullException.ThrowIfNull(utf8Json);
 81
 082            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 083            return jsonTypeInfo.Deserialize(utf8Json);
 084        }
 85
 86        /// <summary>
 87        /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 88        /// The Stream will be read to completion.
 89        /// </summary>
 90        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 91        /// <param name="utf8Json">JSON data to parse.</param>
 92        /// <param name="returnType">The type of the object to convert to and return.</param>
 93        /// <param name="options">Options to control the behavior during reading.</param>
 94        /// <param name="cancellationToken">
 95        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 96        /// </param>
 97        /// <exception cref="System.ArgumentNullException">
 98        /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
 99        /// </exception>
 100        /// <exception cref="JsonException">
 101        /// The JSON is invalid,
 102        /// the <paramref name="returnType"/> is not compatible with the JSON,
 103        /// or when there is remaining data in the Stream.
 104        /// </exception>
 105        /// <exception cref="NotSupportedException">
 106        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 107        /// for <paramref name="returnType"/> or its serializable members.
 108        /// </exception>
 109        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 110        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 111        public static ValueTask<object?> DeserializeAsync(
 112            Stream utf8Json,
 113            Type returnType,
 114            JsonSerializerOptions? options = null,
 115            CancellationToken cancellationToken = default)
 0116        {
 0117            ArgumentNullException.ThrowIfNull(utf8Json);
 0118            ArgumentNullException.ThrowIfNull(returnType);
 119
 0120            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 0121            return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken);
 0122        }
 123
 124        /// <summary>
 125        /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 126        /// The Stream will be read to completion.
 127        /// </summary>
 128        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 129        /// <param name="utf8Json">JSON data to parse.</param>
 130        /// <param name="returnType">The type of the object to convert to and return.</param>
 131        /// <param name="options">Options to control the behavior during reading.</param>
 132        /// <exception cref="System.ArgumentNullException">
 133        /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>.
 134        /// </exception>
 135        /// <exception cref="JsonException">
 136        /// The JSON is invalid,
 137        /// the <paramref name="returnType"/> is not compatible with the JSON,
 138        /// or when there is remaining data in the Stream.
 139        /// </exception>
 140        /// <exception cref="NotSupportedException">
 141        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 142        /// for <paramref name="returnType"/> or its serializable members.
 143        /// </exception>
 144        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 145        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 146        public static object? Deserialize(
 147            Stream utf8Json,
 148            Type returnType,
 149            JsonSerializerOptions? options = null)
 0150        {
 0151            ArgumentNullException.ThrowIfNull(utf8Json);
 0152            ArgumentNullException.ThrowIfNull(returnType);
 153
 0154            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 0155            return jsonTypeInfo.DeserializeAsObject(utf8Json);
 0156        }
 157
 158        /// <summary>
 159        /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 160        /// The Stream will be read to completion.
 161        /// </summary>
 162        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 163        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 164        /// <param name="utf8Json">JSON data to parse.</param>
 165        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 166        /// <param name="cancellationToken">
 167        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 168        /// </param>
 169        /// <exception cref="System.ArgumentNullException">
 170        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 171        /// </exception>
 172        /// <exception cref="JsonException">
 173        /// The JSON is invalid,
 174        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 175        /// or when there is remaining data in the Stream.
 176        /// </exception>
 177        public static ValueTask<TValue?> DeserializeAsync<TValue>(
 178            Stream utf8Json,
 179            JsonTypeInfo<TValue> jsonTypeInfo,
 180            CancellationToken cancellationToken = default)
 0181        {
 0182            ArgumentNullException.ThrowIfNull(utf8Json);
 0183            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 184
 0185            jsonTypeInfo.EnsureConfigured();
 0186            return jsonTypeInfo.DeserializeAsync(utf8Json, cancellationToken);
 0187        }
 188
 189        /// <summary>
 190        /// Reads the UTF-8 encoded text representing a single JSON value into an instance specified by the <paramref na
 191        /// The Stream will be read to completion.
 192        /// </summary>
 193        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 194        /// <param name="utf8Json">JSON data to parse.</param>
 195        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 196        /// <param name="cancellationToken">
 197        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 198        /// </param>
 199        /// <exception cref="System.ArgumentNullException">
 200        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 201        /// </exception>
 202        /// <exception cref="JsonException">
 203        /// The JSON is invalid,
 204        /// or when there is remaining data in the Stream.
 205        /// </exception>
 206        public static ValueTask<object?> DeserializeAsync(
 207            Stream utf8Json,
 208            JsonTypeInfo jsonTypeInfo,
 209            CancellationToken cancellationToken = default)
 0210        {
 0211            ArgumentNullException.ThrowIfNull(utf8Json);
 0212            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 213
 0214            jsonTypeInfo.EnsureConfigured();
 0215            return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken);
 0216        }
 217
 218        /// <summary>
 219        /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>.
 220        /// The Stream will be read to completion.
 221        /// </summary>
 222        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 223        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 224        /// <param name="utf8Json">JSON data to parse.</param>
 225        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 226        /// <exception cref="System.ArgumentNullException">
 227        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 228        /// </exception>
 229        /// <exception cref="JsonException">
 230        /// The JSON is invalid,
 231        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 232        /// or when there is remaining data in the Stream.
 233        /// </exception>
 234        public static TValue? Deserialize<TValue>(
 235            Stream utf8Json,
 236            JsonTypeInfo<TValue> jsonTypeInfo)
 0237        {
 0238            ArgumentNullException.ThrowIfNull(utf8Json);
 0239            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 240
 0241            jsonTypeInfo.EnsureConfigured();
 0242            return jsonTypeInfo.Deserialize(utf8Json);
 0243        }
 244
 245        /// <summary>
 246        /// Reads the UTF-8 encoded text representing a single JSON value into an instance specified by the <paramref na
 247        /// The Stream will be read to completion.
 248        /// </summary>
 249        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 250        /// <param name="utf8Json">JSON data to parse.</param>
 251        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 252        /// <exception cref="System.ArgumentNullException">
 253        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 254        /// </exception>
 255        /// <exception cref="JsonException">
 256        /// The JSON is invalid,
 257        /// or when there is remaining data in the Stream.
 258        /// </exception>
 259        public static object? Deserialize(
 260            Stream utf8Json,
 261            JsonTypeInfo jsonTypeInfo)
 0262        {
 0263            ArgumentNullException.ThrowIfNull(utf8Json);
 0264            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 265
 0266            jsonTypeInfo.EnsureConfigured();
 0267            return jsonTypeInfo.DeserializeAsObject(utf8Json);
 0268        }
 269
 270        /// <summary>
 271        /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 272        /// The Stream will be read to completion.
 273        /// </summary>
 274        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 275        /// <param name="utf8Json">JSON data to parse.</param>
 276        /// <param name="returnType">The type of the object to convert to and return.</param>
 277        /// <param name="context">A metadata provider for serializable types.</param>
 278        /// <param name="cancellationToken">
 279        /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.
 280        /// </param>
 281        /// <exception cref="System.ArgumentNullException">
 282        /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="
 283        /// </exception>
 284        /// <exception cref="JsonException">
 285        /// The JSON is invalid,
 286        /// the <paramref name="returnType"/> is not compatible with the JSON,
 287        /// or when there is remaining data in the Stream.
 288        /// </exception>
 289        /// <exception cref="NotSupportedException">
 290        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 291        /// for <paramref name="returnType"/> or its serializable members.
 292        /// </exception>
 293        /// <exception cref="InvalidOperationException">
 294        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
 295        /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
 296        /// </exception>
 297        public static ValueTask<object?> DeserializeAsync(
 298            Stream utf8Json,
 299            Type returnType,
 300            JsonSerializerContext context,
 301            CancellationToken cancellationToken = default)
 0302        {
 0303            ArgumentNullException.ThrowIfNull(utf8Json);
 0304            ArgumentNullException.ThrowIfNull(returnType);
 0305            ArgumentNullException.ThrowIfNull(context);
 306
 0307            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0308            return jsonTypeInfo.DeserializeAsObjectAsync(utf8Json, cancellationToken);
 0309        }
 310
 311        /// <summary>
 312        /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
 313        /// The Stream will be read to completion.
 314        /// </summary>
 315        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 316        /// <param name="utf8Json">JSON data to parse.</param>
 317        /// <param name="returnType">The type of the object to convert to and return.</param>
 318        /// <param name="context">A metadata provider for serializable types.</param>
 319        /// <exception cref="System.ArgumentNullException">
 320        /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="
 321        /// </exception>
 322        /// <exception cref="JsonException">
 323        /// The JSON is invalid,
 324        /// the <paramref name="returnType"/> is not compatible with the JSON,
 325        /// or when there is remaining data in the Stream.
 326        /// </exception>
 327        /// <exception cref="NotSupportedException">
 328        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 329        /// for <paramref name="returnType"/> or its serializable members.
 330        /// </exception>
 331        /// <exception cref="InvalidOperationException">
 332        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
 333        /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
 334        /// </exception>
 335        public static object? Deserialize(
 336            Stream utf8Json,
 337            Type returnType,
 338            JsonSerializerContext context)
 0339        {
 0340            ArgumentNullException.ThrowIfNull(utf8Json);
 0341            ArgumentNullException.ThrowIfNull(returnType);
 0342            ArgumentNullException.ThrowIfNull(context);
 343
 0344            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0345            return jsonTypeInfo.DeserializeAsObject(utf8Json);
 0346        }
 347
 348        /// <summary>
 349        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 350        /// that can be used to deserialize root-level JSON arrays in a streaming manner.
 351        /// </summary>
 352        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 353        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns>
 354        /// <param name="utf8Json">JSON data to parse.</param>
 355        /// <param name="options">Options to control the behavior during reading.</param>
 356        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 357        /// <exception cref="System.ArgumentNullException">
 358        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 359        /// </exception>
 360        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 361        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 362        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 363            Stream utf8Json,
 364            JsonSerializerOptions? options = null,
 365            CancellationToken cancellationToken = default)
 0366        {
 0367            return DeserializeAsyncEnumerable<TValue>(utf8Json, topLevelValues: false, options, cancellationToken);
 0368        }
 369
 370        /// <summary>
 371        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 372        /// that can be used to deserialize sequences of JSON values in a streaming manner.
 373        /// </summary>
 374        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 375        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON sequence.</returns>
 376        /// <param name="utf8Json">JSON data to parse.</param>
 377        /// <param name="topLevelValues"><see langword="true"/> to deserialize from a sequence of top-level JSON values
 378        /// (for example, a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"
 379        /// <param name="options">Options to control the behavior during reading.</param>
 380        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 381        /// <exception cref="System.ArgumentNullException">
 382        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 383        /// </exception>
 384        /// <remarks>
 385        /// When <paramref name="topLevelValues"/> is set to <see langword="true" />, treats the stream as a sequence of
 386        /// whitespace separated top-level JSON values and attempts to deserialize each value into <typeparamref name="T
 387        /// This is a superset of the <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> format and can be used
 388        /// When <paramref name="topLevelValues"/> is set to <see langword="false" />, treats the stream as a JSON array
 389        /// attempts to deserialize each element into <typeparamref name="TValue"/>.
 390        /// </remarks>
 391        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 392        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 393        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 394            Stream utf8Json,
 395            bool topLevelValues,
 396            JsonSerializerOptions? options = null,
 397            CancellationToken cancellationToken = default)
 0398        {
 0399            ArgumentNullException.ThrowIfNull(utf8Json);
 400
 0401            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 0402            return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, topLevelValues, cancellationToken);
 0403        }
 404
 405        /// <summary>
 406        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 407        /// that can be used to deserialize root-level JSON arrays in a streaming manner.
 408        /// </summary>
 409        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 410        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns>
 411        /// <param name="utf8Json">JSON data to parse.</param>
 412        /// <param name="jsonTypeInfo">Metadata about the element type to convert.</param>
 413        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 414        /// <exception cref="System.ArgumentNullException">
 415        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 416        /// </exception>
 417        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 418            Stream utf8Json,
 419            JsonTypeInfo<TValue> jsonTypeInfo,
 420            CancellationToken cancellationToken = default)
 0421        {
 0422            return DeserializeAsyncEnumerable(utf8Json, jsonTypeInfo, topLevelValues: false, cancellationToken);
 0423        }
 424
 425        /// <summary>
 426        /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" />
 427        /// that can be used to deserialize sequences of JSON values in a streaming manner.
 428        /// </summary>
 429        /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam>
 430        /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON sequence.</returns>
 431        /// <param name="utf8Json">JSON data to parse.</param>
 432        /// <param name="jsonTypeInfo">Metadata about the element type to convert.</param>
 433        /// <param name="topLevelValues"><see langword="true"/> to deserialize from a sequence of top-level JSON values
 434        /// (for example, a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"
 435        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 436        /// <exception cref="System.ArgumentNullException">
 437        /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 438        /// </exception>
 439        /// <remarks>
 440        /// When <paramref name="topLevelValues"/> is set to <see langword="true" />, treats the stream as a sequence of
 441        /// whitespace separated top-level JSON values and attempts to deserialize each value into <typeparamref name="T
 442        /// This is a superset of the <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> format and can be used
 443        /// When <paramref name="topLevelValues"/> is set to <see langword="false" />, treats the stream as a JSON array
 444        /// attempts to deserialize each element into <typeparamref name="TValue"/>.
 445        /// </remarks>
 446        public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>(
 447            Stream utf8Json,
 448            JsonTypeInfo<TValue> jsonTypeInfo,
 449            bool topLevelValues,
 450            CancellationToken cancellationToken = default)
 0451        {
 0452            ArgumentNullException.ThrowIfNull(utf8Json);
 0453            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 454
 0455            jsonTypeInfo.EnsureConfigured();
 0456            return DeserializeAsyncEnumerableCore(utf8Json, jsonTypeInfo, topLevelValues, cancellationToken);
 0457        }
 458
 459        private static IAsyncEnumerable<T?> DeserializeAsyncEnumerableCore<T>(
 460            Stream utf8Json,
 461            JsonTypeInfo<T> jsonTypeInfo,
 462            bool topLevelValues,
 463            CancellationToken cancellationToken)
 0464        {
 0465            Debug.Assert(jsonTypeInfo.IsConfigured);
 466
 467            JsonTypeInfo<List<T?>> listTypeInfo;
 0468            JsonReaderOptions readerOptions = jsonTypeInfo.Options.GetReaderOptions();
 0469            if (topLevelValues)
 0470            {
 0471                listTypeInfo = GetOrAddListTypeInfoForRootLevelValueMode(jsonTypeInfo);
 0472                readerOptions.AllowMultipleValues = true;
 0473            }
 474            else
 0475            {
 0476                listTypeInfo = GetOrAddListTypeInfoForArrayMode(jsonTypeInfo);
 0477            }
 478
 0479            return CreateAsyncEnumerableFromArray(utf8Json, listTypeInfo, readerOptions, cancellationToken);
 480
 481            static async IAsyncEnumerable<T?> CreateAsyncEnumerableFromArray(
 482                Stream utf8Json,
 483                JsonTypeInfo<List<T?>> listTypeInfo,
 484                JsonReaderOptions readerOptions,
 485                [EnumeratorCancellation] CancellationToken cancellationToken)
 0486            {
 0487                Debug.Assert(listTypeInfo.IsConfigured);
 488
 0489                ReadStack readStack = default;
 0490                readStack.Initialize(listTypeInfo, supportContinuation: true);
 0491                JsonReaderState jsonReaderState = new(readerOptions);
 492                // Note: The StreamReadBufferState ctor rents pooled buffers.
 0493                StreamReadBufferState bufferState = new StreamReadBufferState(listTypeInfo.Options.DefaultBufferSize);
 494
 495                try
 0496                {
 497                    bool success;
 498                    do
 0499                    {
 0500                        bufferState = await bufferState.ReadAsync(utf8Json, cancellationToken, fillBuffer: false).Config
 0501                        success = listTypeInfo.ContinueDeserialize<StreamReadBufferState, Stream>(
 0502                            ref bufferState,
 0503                            ref jsonReaderState,
 0504                            ref readStack,
 0505                            out List<T?>? _);
 506
 0507                        if (readStack.Current.ReturnValue is { } returnValue)
 0508                        {
 0509                            var list = (List<T?>)returnValue;
 0510                            foreach (T? item in list)
 0511                            {
 0512                                yield return item;
 0513                            }
 514
 0515                            list.Clear();
 0516                        }
 517
 0518                    } while (!success);
 0519                }
 520                finally
 0521                {
 0522                    bufferState.Dispose();
 0523                }
 0524            }
 0525        }
 526    }
 527}
 528

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs

#LineLine coverage
 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
 4using System.Buffers;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.Text.Json.Serialization;
 8using System.Text.Json.Serialization.Metadata;
 9
 10namespace System.Text.Json
 11{
 12    /// <summary>
 13    /// Provides functionality to serialize objects or value types to JSON and
 14    /// deserialize JSON into objects or value types.
 15    /// </summary>
 16    public static partial class JsonSerializer
 17    {
 18        /// <summary>
 19        /// Parses the text representing a single JSON value into a <typeparamref name="TValue"/>.
 20        /// </summary>
 21        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 22        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 23        /// <param name="json">JSON text to parse.</param>
 24        /// <param name="options">Options to control the behavior during parsing.</param>
 25        /// <exception cref="System.ArgumentNullException">
 26        /// <paramref name="json"/> is <see langword="null"/>.
 27        /// </exception>
 28        /// <exception cref="JsonException">
 29        /// The JSON is invalid.
 30        ///
 31        /// -or-
 32        ///
 33        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 34        ///
 35        /// -or-
 36        ///
 37        /// There is remaining data in the string beyond a single JSON value.</exception>
 38        /// <exception cref="NotSupportedException">
 39        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 40        /// for <typeparamref name="TValue"/> or its serializable members.
 41        /// </exception>
 42        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 43        /// UTF-8 methods since the implementation natively uses UTF-8.
 44        /// </remarks>
 45        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 46        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 47        public static TValue? Deserialize<TValue>([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonSerializer
 048        {
 049            ArgumentNullException.ThrowIfNull(json);
 50
 051            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 052            return ReadFromSpan(json.AsSpan(), jsonTypeInfo);
 053        }
 54
 55        /// <summary>
 56        /// Parses the text representing a single JSON value into an instance of the type specified by a generic type pa
 57        /// </summary>
 58        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 59        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 60        /// <param name="json">The JSON text to parse.</param>
 61        /// <param name="options">Options to control the behavior during parsing.</param>
 62        /// <exception cref="JsonException">
 63        /// The JSON is invalid.
 64        ///
 65        /// -or-
 66        ///
 67        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 68        ///
 69        /// -or-
 70        ///
 71        /// There is remaining data in the span beyond a single JSON value.</exception>
 72        /// <exception cref="NotSupportedException">
 73        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 74        /// for <typeparamref name="TValue"/> or its serializable members.
 75        /// </exception>
 76        /// <remarks>Using a UTF-16 span is not as efficient as using the
 77        /// UTF-8 methods since the implementation natively uses UTF-8.
 78        /// </remarks>
 79        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 80        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 81        public static TValue? Deserialize<TValue>([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan<char> json, Js
 082        {
 083            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 084            return ReadFromSpan(json, jsonTypeInfo);
 085        }
 86
 87        /// <summary>
 88        /// Parses the text representing a single JSON value into a <paramref name="returnType"/>.
 89        /// </summary>
 90        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 91        /// <param name="json">JSON text to parse.</param>
 92        /// <param name="returnType">The type of the object to convert to and return.</param>
 93        /// <param name="options">Options to control the behavior during parsing.</param>
 94        /// <exception cref="System.ArgumentNullException">
 95        /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>.
 96        /// </exception>
 97        /// <exception cref="JsonException">
 98        /// The JSON is invalid.
 99        ///
 100        /// -or-
 101        ///
 102        /// <paramref name="returnType"/> is not compatible with the JSON.
 103        ///
 104        /// -or-
 105        ///
 106        /// There is remaining data in the string beyond a single JSON value.</exception>
 107        /// <exception cref="NotSupportedException">
 108        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 109        /// for <paramref name="returnType"/> or its serializable members.
 110        /// </exception>
 111        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 112        /// UTF-8 methods since the implementation natively uses UTF-8.
 113        /// </remarks>
 114        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 115        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 116        public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, Type returnType, JsonS
 0117        {
 0118            ArgumentNullException.ThrowIfNull(json);
 0119            ArgumentNullException.ThrowIfNull(returnType);
 120
 0121            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 0122            return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo);
 0123        }
 124
 125        /// <summary>
 126        /// Parses the text representing a single JSON value into an instance of a specified type.
 127        /// </summary>
 128        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 129        /// <param name="json">The JSON text to parse.</param>
 130        /// <param name="returnType">The type of the object to convert to and return.</param>
 131        /// <param name="options">Options to control the behavior during parsing.</param>
 132        /// <exception cref="System.ArgumentNullException">
 133        /// <paramref name="returnType"/> is <see langword="null"/>.
 134        /// </exception>
 135        /// <exception cref="JsonException">
 136        /// The JSON is invalid.
 137        ///
 138        /// -or-
 139        ///
 140        /// <paramref name="returnType"/> is not compatible with the JSON.
 141        ///
 142        /// -or-
 143        ///
 144        /// There is remaining data in the span beyond a single JSON value.</exception>
 145        /// <exception cref="NotSupportedException">
 146        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 147        /// for <paramref name="returnType"/> or its serializable members.
 148        /// </exception>
 149        /// <remarks>Using a UTF-16 span is not as efficient as using the
 150        /// UTF-8 methods since the implementation natively uses UTF-8.
 151        /// </remarks>
 152        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 153        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 154        public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan<char> json, Type retur
 0155        {
 0156            ArgumentNullException.ThrowIfNull(returnType);
 157
 158            // default/null span is treated as empty
 159
 0160            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 0161            return ReadFromSpanAsObject(json, jsonTypeInfo);
 0162        }
 163
 164        /// <summary>
 165        /// Parses the text representing a single JSON value into a <typeparamref name="TValue"/>.
 166        /// </summary>
 167        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 168        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 169        /// <param name="json">JSON text to parse.</param>
 170        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 171        /// <exception cref="System.ArgumentNullException">
 172        /// <paramref name="json"/> is <see langword="null"/>.
 173        ///
 174        /// -or-
 175        ///
 176        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 177        /// </exception>
 178        /// <exception cref="JsonException">
 179        /// The JSON is invalid.
 180        ///
 181        /// -or-
 182        ///
 183        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 184        ///
 185        /// -or-
 186        ///
 187        /// There is remaining data in the string beyond a single JSON value.</exception>
 188        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 189        /// UTF-8 methods since the implementation natively uses UTF-8.
 190        /// </remarks>
 191        public static TValue? Deserialize<TValue>([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonTypeInfo<T
 0192        {
 0193            ArgumentNullException.ThrowIfNull(json);
 0194            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 195
 0196            jsonTypeInfo.EnsureConfigured();
 0197            return ReadFromSpan(json.AsSpan(), jsonTypeInfo);
 0198        }
 199
 200        /// <summary>
 201        /// Parses the text representing a single JSON value into a <typeparamref name="TValue"/>.
 202        /// </summary>
 203        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 204        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 205        /// <param name="json">JSON text to parse.</param>
 206        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 207        /// <exception cref="System.ArgumentNullException">
 208        /// <paramref name="json"/> is <see langword="null"/>.
 209        ///
 210        /// -or-
 211        ///
 212        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 213        /// </exception>
 214        /// <exception cref="JsonException">
 215        /// The JSON is invalid.
 216        ///
 217        /// -or-
 218        ///
 219        /// <typeparamref name="TValue" /> is not compatible with the JSON.
 220        ///
 221        /// -or-
 222        ///
 223        /// There is remaining data in the string beyond a single JSON value.</exception>
 224        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 225        /// UTF-8 methods since the implementation natively uses UTF-8.
 226        /// </remarks>
 227        public static TValue? Deserialize<TValue>([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan<char> json, Js
 0228        {
 0229            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 230
 0231            jsonTypeInfo.EnsureConfigured();
 0232            return ReadFromSpan(json, jsonTypeInfo);
 0233        }
 234
 235        /// <summary>
 236        /// Parses the text representing a single JSON value into an instance specified by the <paramref name="jsonTypeI
 237        /// </summary>
 238        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 239        /// <param name="json">JSON text to parse.</param>
 240        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 241        /// <exception cref="System.ArgumentNullException">
 242        /// <paramref name="json"/> is <see langword="null"/>.
 243        ///
 244        /// -or-
 245        ///
 246        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 247        /// </exception>
 248        /// <exception cref="JsonException">
 249        /// The JSON is invalid.
 250        ///
 251        /// -or-
 252        ///
 253        /// There is remaining data in the string beyond a single JSON value.</exception>
 254        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 255        /// UTF-8 methods since the implementation natively uses UTF-8.
 256        /// </remarks>
 257        public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonTypeInfo jsonTypeI
 0258        {
 0259            ArgumentNullException.ThrowIfNull(json);
 0260            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 261
 0262            jsonTypeInfo.EnsureConfigured();
 0263            return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo);
 0264        }
 265
 266        /// <summary>
 267        /// Parses the text representing a single JSON value into an instance specified by the <paramref name="jsonTypeI
 268        /// </summary>
 269        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 270        /// <param name="json">JSON text to parse.</param>
 271        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 272        /// <exception cref="System.ArgumentNullException">
 273        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 274        /// </exception>
 275        /// <exception cref="JsonException">
 276        /// The JSON is invalid.
 277        ///
 278        /// -or-
 279        ///
 280        /// There is remaining data in the string beyond a single JSON value.</exception>
 281        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 282        /// UTF-8 methods since the implementation natively uses UTF-8.
 283        /// </remarks>
 284        public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan<char> json, JsonTypeIn
 0285        {
 0286            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 287
 0288            jsonTypeInfo.EnsureConfigured();
 0289            return ReadFromSpanAsObject(json, jsonTypeInfo);
 0290        }
 291
 292        /// <summary>
 293        /// Parses the text representing a single JSON value into a <paramref name="returnType"/>.
 294        /// </summary>
 295        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 296        /// <param name="json">JSON text to parse.</param>
 297        /// <param name="returnType">The type of the object to convert to and return.</param>
 298        /// <param name="context">A metadata provider for serializable types.</param>
 299        /// <exception cref="System.ArgumentNullException">
 300        /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>.
 301        ///
 302        /// -or-
 303        ///
 304        /// <paramref name="context"/> is <see langword="null"/>.
 305        /// </exception>
 306        /// <exception cref="JsonException">
 307        /// The JSON is invalid.
 308        ///
 309        /// -or-
 310        ///
 311        /// <paramref name="returnType" /> is not compatible with the JSON.
 312        ///
 313        /// -or-
 314        ///
 315        /// There is remaining data in the string beyond a single JSON value.</exception>
 316        /// <exception cref="NotSupportedException">
 317        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 318        /// for <paramref name="returnType"/> or its serializable members.
 319        /// </exception>
 320        /// <exception cref="InvalidOperationException">
 321        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 322        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 323        /// </exception>
 324        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 325        /// UTF-8 methods since the implementation natively uses UTF-8.
 326        /// </remarks>
 327        public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, Type returnType, JsonS
 0328        {
 0329            ArgumentNullException.ThrowIfNull(json);
 0330            ArgumentNullException.ThrowIfNull(returnType);
 0331            ArgumentNullException.ThrowIfNull(context);
 332
 0333            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0334            return ReadFromSpanAsObject(json.AsSpan(), jsonTypeInfo);
 0335        }
 336
 337        /// <summary>
 338        /// Parses the text representing a single JSON value into a <paramref name="returnType"/>.
 339        /// </summary>
 340        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 341        /// <param name="json">JSON text to parse.</param>
 342        /// <param name="returnType">The type of the object to convert to and return.</param>
 343        /// <param name="context">A metadata provider for serializable types.</param>
 344        /// <exception cref="System.ArgumentNullException">
 345        /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>.
 346        ///
 347        /// -or-
 348        ///
 349        /// <paramref name="context"/> is <see langword="null"/>.
 350        /// </exception>
 351        /// <exception cref="JsonException">
 352        /// The JSON is invalid.
 353        ///
 354        /// -or-
 355        ///
 356        /// <paramref name="returnType" /> is not compatible with the JSON.
 357        ///
 358        /// -or-
 359        ///
 360        /// There is remaining data in the string beyond a single JSON value.</exception>
 361        /// <exception cref="NotSupportedException">
 362        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 363        /// for <paramref name="returnType"/> or its serializable members.
 364        /// </exception>
 365        /// <exception cref="InvalidOperationException">
 366        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 367        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 368        /// </exception>
 369        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
 370        /// UTF-8 methods since the implementation natively uses UTF-8.
 371        /// </remarks>
 372        public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan<char> json, Type retur
 0373        {
 0374            ArgumentNullException.ThrowIfNull(returnType);
 0375            ArgumentNullException.ThrowIfNull(context);
 376
 0377            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType);
 0378            return ReadFromSpanAsObject(json, jsonTypeInfo);
 0379        }
 380
 381        private static unsafe TValue? ReadFromSpan<TValue>(ReadOnlySpan<char> json, JsonTypeInfo<TValue> jsonTypeInfo)
 0382        {
 0383            Debug.Assert(jsonTypeInfo.IsConfigured);
 0384            byte[]? tempArray = null;
 385
 386            // For performance, avoid obtaining actual byte count unless memory usage is higher than the threshold.
 0387            Span<byte> utf8 =
 0388                // Use stack memory
 0389                json.Length <= (JsonConstants.StackallocByteThreshold / JsonConstants.MaxExpansionFactorWhileTranscoding
 0390                // Use a pooled array
 0391                json.Length <= (JsonConstants.ArrayPoolMaxSizeBeforeUsingNormalAlloc / JsonConstants.MaxExpansionFactorW
 0392                // Use a normal alloc since the pool would create a normal alloc anyway based on the threshold (per curr
 0393                // and by using a normal alloc we can avoid the Clear().
 0394                new byte[JsonReaderHelper.GetUtf8ByteCount(json)];
 395
 396            try
 0397            {
 0398                int actualByteCount = JsonReaderHelper.GetUtf8FromText(json, utf8);
 0399                utf8 = utf8.Slice(0, actualByteCount);
 0400                return ReadFromSpan(utf8, jsonTypeInfo, actualByteCount);
 401            }
 402            finally
 0403            {
 0404                if (tempArray is not null)
 0405                {
 0406                    utf8.Clear();
 0407                    ArrayPool<byte>.Shared.Return(tempArray);
 0408                }
 0409            }
 0410        }
 411
 412        private static unsafe object? ReadFromSpanAsObject(ReadOnlySpan<char> json, JsonTypeInfo jsonTypeInfo)
 0413        {
 0414            Debug.Assert(jsonTypeInfo.IsConfigured);
 0415            byte[]? tempArray = null;
 416
 417            // For performance, avoid obtaining actual byte count unless memory usage is higher than the threshold.
 0418            Span<byte> utf8 =
 0419                // Use stack memory
 0420                json.Length <= (JsonConstants.StackallocByteThreshold / JsonConstants.MaxExpansionFactorWhileTranscoding
 0421                // Use a pooled array
 0422                json.Length <= (JsonConstants.ArrayPoolMaxSizeBeforeUsingNormalAlloc / JsonConstants.MaxExpansionFactorW
 0423                // Use a normal alloc since the pool would create a normal alloc anyway based on the threshold (per curr
 0424                // and by using a normal alloc we can avoid the Clear().
 0425                new byte[JsonReaderHelper.GetUtf8ByteCount(json)];
 426
 427            try
 0428            {
 0429                int actualByteCount = JsonReaderHelper.GetUtf8FromText(json, utf8);
 0430                utf8 = utf8.Slice(0, actualByteCount);
 0431                return ReadFromSpanAsObject(utf8, jsonTypeInfo, actualByteCount);
 432            }
 433            finally
 0434            {
 0435                if (tempArray is not null)
 0436                {
 0437                    utf8.Clear();
 0438                    ArrayPool<byte>.Shared.Return(tempArray);
 0439                }
 0440            }
 0441        }
 442    }
 443}
 444

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs

#LineLine coverage
 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
 4using System.Buffers;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.Text.Json.Serialization;
 8using System.Text.Json.Serialization.Metadata;
 9
 10namespace System.Text.Json
 11{
 12    public static partial class JsonSerializer
 13    {
 14        /// <summary>
 15        /// Reads one JSON value (including objects or arrays) from the provided reader into a <typeparamref name="TValu
 16        /// </summary>
 17        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 18        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 19        /// <param name="reader">The reader to read.</param>
 20        /// <param name="options">Options to control the serializer behavior during reading.</param>
 21        /// <exception cref="JsonException">
 22        /// The JSON is invalid,
 23        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 24        /// or a value could not be read from the reader.
 25        /// </exception>
 26        /// <exception cref="ArgumentException">
 27        ///   <paramref name="reader"/> is using unsupported options.
 28        /// </exception>
 29        /// <exception cref="NotSupportedException">
 30        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 31        /// for <typeparamref name="TValue"/> or its serializable members.
 32        /// </exception>
 33        /// <remarks>
 34        ///   <para>
 35        ///     If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/>
 36        ///     is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the
 37        ///     reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine
 38        ///     the start of the value.
 39        ///   </para>
 40        ///
 41        ///   <para>
 42        ///     Upon completion of this method, <paramref name="reader"/> will be positioned at the
 43        ///     final token in the JSON value. If an exception is thrown, the reader is reset to
 44        ///     the state it was in when the method was called.
 45        ///   </para>
 46        ///
 47        ///   <para>
 48        ///     This method makes a copy of the data the reader acted on, so there is no caller
 49        ///     requirement to maintain data integrity beyond the return of this method.
 50        ///   </para>
 51        ///
 52        ///   <para>
 53        ///     The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take
 54        ///     Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, an
 55        ///   </para>
 56        /// </remarks>
 57        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 58        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 59        public static TValue? Deserialize<TValue>(ref Utf8JsonReader reader, JsonSerializerOptions? options = null)
 060        {
 061            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 062            return Read<TValue>(ref reader, jsonTypeInfo);
 063        }
 64
 65        /// <summary>
 66        /// Reads one JSON value (including objects or arrays) from the provided reader into a <paramref name="returnTyp
 67        /// </summary>
 68        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 69        /// <param name="reader">The reader to read.</param>
 70        /// <param name="returnType">The type of the object to convert to and return.</param>
 71        /// <param name="options">Options to control the serializer behavior during reading.</param>
 72        /// <exception cref="ArgumentNullException">
 73        /// <paramref name="returnType"/> is <see langword="null"/>.
 74        /// </exception>
 75        /// <exception cref="JsonException">
 76        /// The JSON is invalid,
 77        /// <paramref name="returnType"/> is not compatible with the JSON,
 78        /// or a value could not be read from the reader.
 79        /// </exception>
 80        /// <exception cref="ArgumentException">
 81        ///   <paramref name="reader"/> is using unsupported options.
 82        /// </exception>
 83        /// <exception cref="NotSupportedException">
 84        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 85        /// for <paramref name="returnType"/> or its serializable members.
 86        /// </exception>
 87        /// <remarks>
 88        ///   <para>
 89        ///     If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/>
 90        ///     is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the
 91        ///     reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine
 92        ///     the start of the value.
 93        ///   </para>
 94        ///
 95        ///   <para>
 96        ///     Upon completion of this method, <paramref name="reader"/> will be positioned at the
 97        ///     final token in the JSON value. If an exception is thrown, the reader is reset to
 98        ///     the state it was in when the method was called.
 99        ///   </para>
 100        ///
 101        ///   <para>
 102        ///     This method makes a copy of the data the reader acted on, so there is no caller
 103        ///     requirement to maintain data integrity beyond the return of this method.
 104        ///   </para>
 105        ///   <para>
 106        ///     The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take
 107        ///     Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, an
 108        ///   </para>
 109        /// </remarks>
 110        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 111        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 112        public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions? options = n
 0113        {
 0114            ArgumentNullException.ThrowIfNull(returnType);
 115
 0116            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType);
 0117            return ReadAsObject(ref reader, jsonTypeInfo);
 0118        }
 119
 120        /// <summary>
 121        /// Reads one JSON value (including objects or arrays) from the provided reader into a <typeparamref name="TValu
 122        /// </summary>
 123        /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam>
 124        /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns>
 125        /// <param name="reader">The reader to read.</param>
 126        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 127        /// <exception cref="JsonException">
 128        /// The JSON is invalid,
 129        /// <typeparamref name="TValue"/> is not compatible with the JSON,
 130        /// or a value could not be read from the reader.
 131        /// </exception>
 132        /// <exception cref="ArgumentException">
 133        ///   <paramref name="reader"/> is using unsupported options.
 134        /// </exception>
 135        /// <remarks>
 136        ///   <para>
 137        ///     If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/>
 138        ///     is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the
 139        ///     reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine
 140        ///     the start of the value.
 141        ///   </para>
 142        ///
 143        ///   <para>
 144        ///     Upon completion of this method, <paramref name="reader"/> will be positioned at the
 145        ///     final token in the JSON value. If an exception is thrown, the reader is reset to
 146        ///     the state it was in when the method was called.
 147        ///   </para>
 148        ///
 149        ///   <para>
 150        ///     This method makes a copy of the data the reader acted on, so there is no caller
 151        ///     requirement to maintain data integrity beyond the return of this method.
 152        ///   </para>
 153        ///
 154        ///   <para>
 155        ///     The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take
 156        ///     Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, an
 157        ///   </para>
 158        /// </remarks>
 159        public static TValue? Deserialize<TValue>(ref Utf8JsonReader reader, JsonTypeInfo<TValue> jsonTypeInfo)
 0160        {
 0161            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 162
 0163            jsonTypeInfo.EnsureConfigured();
 0164            return Read(ref reader, jsonTypeInfo);
 0165        }
 166
 167        /// <summary>
 168        /// Reads one JSON value (including objects or arrays) from the provided reader into an instance specified by th
 169        /// </summary>
 170        /// <returns>A <paramref name="jsonTypeInfo"/> representation of the JSON value.</returns>
 171        /// <param name="reader">The reader to read.</param>
 172        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 173        /// <exception cref="JsonException">
 174        /// The JSON is invalid,
 175        /// <paramref name="jsonTypeInfo"/> is not compatible with the JSON,
 176        /// or a value could not be read from the reader.
 177        /// </exception>
 178        /// <exception cref="ArgumentException">
 179        ///   <paramref name="reader"/> is using unsupported options.
 180        /// </exception>
 181        /// <remarks>
 182        ///   <para>
 183        ///     If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/>
 184        ///     is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the
 185        ///     reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine
 186        ///     the start of the value.
 187        ///   </para>
 188        ///
 189        ///   <para>
 190        ///     Upon completion of this method, <paramref name="reader"/> will be positioned at the
 191        ///     final token in the JSON value. If an exception is thrown, the reader is reset to
 192        ///     the state it was in when the method was called.
 193        ///   </para>
 194        ///
 195        ///   <para>
 196        ///     This method makes a copy of the data the reader acted on, so there is no caller
 197        ///     requirement to maintain data integrity beyond the return of this method.
 198        ///   </para>
 199        ///
 200        ///   <para>
 201        ///     The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take
 202        ///     Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, an
 203        ///   </para>
 204        /// </remarks>
 205        public static object? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo)
 0206        {
 0207            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 208
 0209            jsonTypeInfo.EnsureConfigured();
 0210            return ReadAsObject(ref reader, jsonTypeInfo);
 0211        }
 212
 213        /// <summary>
 214        /// Reads one JSON value (including objects or arrays) from the provided reader into a <paramref name="returnTyp
 215        /// </summary>
 216        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
 217        /// <param name="reader">The reader to read.</param>
 218        /// <param name="returnType">The type of the object to convert to and return.</param>
 219        /// <param name="context">A metadata provider for serializable types.</param>
 220        /// <exception cref="ArgumentNullException">
 221        /// <paramref name="returnType"/> or <paramref name="context"/> is <see langword="null"/>.
 222        /// </exception>
 223        /// <exception cref="JsonException">
 224        /// The JSON is invalid,
 225        /// <paramref name="returnType"/> is not compatible with the JSON,
 226        /// or a value could not be read from the reader.
 227        /// </exception>
 228        /// <exception cref="ArgumentException">
 229        ///   <paramref name="reader"/> is using unsupported options.
 230        /// </exception>
 231        /// <exception cref="NotSupportedException">
 232        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 233        /// for <paramref name="returnType"/> or its serializable members.
 234        /// </exception>
 235        /// <exception cref="InvalidOperationException">
 236        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/>
 237        /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>.
 238        /// </exception>
 239        /// <remarks>
 240        ///   <para>
 241        ///     If the <see cref="Utf8JsonReader.TokenType"/> property of <paramref name="reader"/>
 242        ///     is <see cref="JsonTokenType.PropertyName"/> or <see cref="JsonTokenType.None"/>, the
 243        ///     reader will be advanced by one call to <see cref="Utf8JsonReader.Read"/> to determine
 244        ///     the start of the value.
 245        ///   </para>
 246        ///
 247        ///   <para>
 248        ///     Upon completion of this method, <paramref name="reader"/> will be positioned at the
 249        ///     final token in the JSON value. If an exception is thrown, the reader is reset to
 250        ///     the state it was in when the method was called.
 251        ///   </para>
 252        ///
 253        ///   <para>
 254        ///     This method makes a copy of the data the reader acted on, so there is no caller
 255        ///     requirement to maintain data integrity beyond the return of this method.
 256        ///   </para>
 257        ///   <para>
 258        ///     The <see cref="JsonReaderOptions"/> used to create the instance of the <see cref="Utf8JsonReader"/> take
 259        ///     Hence, <see cref="JsonReaderOptions.AllowTrailingCommas"/>, <see cref="JsonReaderOptions.MaxDepth"/>, an
 260        ///   </para>
 261        /// </remarks>
 262        public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerContext context)
 0263        {
 0264            ArgumentNullException.ThrowIfNull(returnType);
 0265            ArgumentNullException.ThrowIfNull(context);
 266
 0267            return ReadAsObject(ref reader, GetTypeInfo(context, returnType));
 0268        }
 269
 270        private static TValue? Read<TValue>(ref Utf8JsonReader reader, JsonTypeInfo<TValue> jsonTypeInfo)
 0271        {
 0272            Debug.Assert(jsonTypeInfo.IsConfigured);
 273
 0274            if (reader.CurrentState.Options.CommentHandling == JsonCommentHandling.Allow)
 0275            {
 0276                ThrowHelper.ThrowArgumentException_SerializerDoesNotSupportComments(nameof(reader));
 277            }
 278
 0279            ReadStack state = default;
 0280            state.Initialize(jsonTypeInfo);
 0281            Utf8JsonReader restore = reader;
 282
 283            try
 0284            {
 0285                Utf8JsonReader scopedReader = GetReaderScopedToNextValue(ref reader, ref state);
 0286                return jsonTypeInfo.Deserialize(ref scopedReader, ref state);
 287            }
 0288            catch (JsonException)
 0289            {
 0290                reader = restore;
 0291                throw;
 292            }
 0293        }
 294
 295        private static object? ReadAsObject(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo)
 0296        {
 0297            Debug.Assert(jsonTypeInfo.IsConfigured);
 298
 0299            if (reader.CurrentState.Options.CommentHandling == JsonCommentHandling.Allow)
 0300            {
 0301                ThrowHelper.ThrowArgumentException_SerializerDoesNotSupportComments(nameof(reader));
 302            }
 303
 0304            ReadStack state = default;
 0305            state.Initialize(jsonTypeInfo);
 0306            Utf8JsonReader restore = reader;
 307
 308            try
 0309            {
 0310                Utf8JsonReader scopedReader = GetReaderScopedToNextValue(ref reader, ref state);
 0311                return jsonTypeInfo.DeserializeAsObject(ref scopedReader, ref state);
 312            }
 0313            catch (JsonException)
 0314            {
 0315                reader = restore;
 0316                throw;
 317            }
 0318        }
 319
 320        private static Utf8JsonReader GetReaderScopedToNextValue(ref Utf8JsonReader reader, scoped ref ReadStack state)
 0321        {
 322            // Advances the provided reader, validating that it is pointing to a complete JSON value.
 323            // If successful, returns a new Utf8JsonReader that is scoped to the next value, reusing existing buffers.
 324
 0325            ReadOnlySpan<byte> valueSpan = default;
 0326            ReadOnlySequence<byte> valueSequence = default;
 327
 0328            long lineNumber = 0;
 0329            long bytePositionInLine = 0;
 330
 331            try
 0332            {
 0333                switch (reader.TokenType)
 334                {
 335                    // A new reader was created and has never been read,
 336                    // so we need to move to the first token.
 337                    // (or a reader has terminated and we're about to throw)
 338                    case JsonTokenType.None:
 339                    // Using a reader loop the caller has identified a property they wish to
 340                    // hydrate into a JsonDocument. Move to the value first.
 341                    case JsonTokenType.PropertyName:
 0342                        {
 0343                            if (!reader.Read())
 0344                            {
 0345                                ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.ExpectedOneCompleteTo
 346                            }
 0347                            break;
 348                        }
 349                }
 350
 351                // Capture the original reader's position so that the scoped reader, after consuming its
 352                // first token, lands on the same position the original reader is currently at.
 353                // The values captured here represent the position immediately after the current token,
 354                // the per-case logic below rewinds them to the position immediately before the value token starts.
 0355                lineNumber = reader.CurrentState._lineNumber;
 0356                bytePositionInLine = reader.CurrentState._bytePositionInLine;
 357
 0358                switch (reader.TokenType)
 359                {
 360                    // Any of the "value start" states are acceptable.
 361                    case JsonTokenType.StartObject:
 362                    case JsonTokenType.StartArray:
 0363                        long startingOffset = reader.TokenStartIndex;
 364
 0365                        if (!reader.TrySkip())
 0366                        {
 0367                            ThrowHelper.ThrowJsonReaderException(ref reader, ExceptionResource.NotEnoughData);
 368                        }
 369
 0370                        long totalLength = reader.BytesConsumed - startingOffset;
 0371                        ReadOnlySequence<byte> sequence = reader.OriginalSequence;
 372
 0373                        if (sequence.IsEmpty)
 0374                        {
 0375                            valueSpan = reader.OriginalSpan.Slice(
 0376                                checked((int)startingOffset),
 0377                                checked((int)totalLength));
 0378                        }
 379                        else
 0380                        {
 0381                            valueSequence = sequence.Slice(startingOffset, totalLength);
 0382                        }
 383
 384                        // Rewind by 1 byte to point right before the opening '{' or '['.
 0385                        bytePositionInLine--;
 0386                        Debug.Assert(reader.TokenType is JsonTokenType.EndObject or JsonTokenType.EndArray);
 0387                        break;
 388
 389                    // Single-token values
 390                    case JsonTokenType.Number:
 391                    case JsonTokenType.True:
 392                    case JsonTokenType.False:
 393                    case JsonTokenType.Null:
 394                        // Rewind by the length of the value token to point right before the start of the value.
 0395                        if (reader.HasValueSequence)
 0396                        {
 0397                            valueSequence = reader.ValueSequence;
 0398                            bytePositionInLine -= valueSequence.Length;
 0399                        }
 400                        else
 0401                        {
 0402                            valueSpan = reader.ValueSpan;
 0403                            bytePositionInLine -= valueSpan.Length;
 0404                        }
 405
 0406                        break;
 407
 408                    // String's ValueSequence/ValueSpan omits the quotes, we need them back.
 409                    case JsonTokenType.String:
 0410                        ReadOnlySequence<byte> originalSequence = reader.OriginalSequence;
 411
 0412                        if (originalSequence.IsEmpty)
 0413                        {
 414                            // Since the quoted string fit in a ReadOnlySpan originally
 415                            // the contents length plus the two quotes can't overflow.
 0416                            int payloadLength = reader.ValueSpan.Length + 2;
 0417                            Debug.Assert(payloadLength > 1);
 418
 0419                            ReadOnlySpan<byte> readerSpan = reader.OriginalSpan;
 420
 0421                            Debug.Assert(
 0422                                readerSpan[(int)reader.TokenStartIndex] == (byte)'"',
 0423                                $"Calculated span starts with {readerSpan[(int)reader.TokenStartIndex]}");
 424
 0425                            Debug.Assert(
 0426                                readerSpan[(int)reader.TokenStartIndex + payloadLength - 1] == (byte)'"',
 0427                                $"Calculated span ends with {readerSpan[(int)reader.TokenStartIndex + payloadLength - 1]
 428
 0429                            valueSpan = readerSpan.Slice((int)reader.TokenStartIndex, payloadLength);
 430
 431                            // Rewind by payloadLength to point right before the opening quote.
 0432                            bytePositionInLine -= payloadLength;
 0433                        }
 434                        else
 0435                        {
 0436                            long payloadLength = reader.HasValueSequence
 0437                                ? reader.ValueSequence.Length + 2
 0438                                : reader.ValueSpan.Length + 2;
 439
 0440                            valueSequence = originalSequence.Slice(reader.TokenStartIndex, payloadLength);
 0441                            Debug.Assert(
 0442                                valueSequence.First.Span[0] == (byte)'"',
 0443                                $"Calculated sequence starts with {valueSequence.First.Span[0]}");
 444
 0445                            Debug.Assert(
 0446                                valueSequence.ToArray()[payloadLength - 1] == (byte)'"',
 0447                                $"Calculated sequence ends with {valueSequence.ToArray()[payloadLength - 1]}");
 448
 449                            // Rewind by payloadLength to point right before the opening quote.
 0450                            bytePositionInLine -= payloadLength;
 0451                        }
 452
 0453                        break;
 454
 455                    default:
 0456                        byte displayByte = reader.HasValueSequence
 0457                            ? reader.ValueSequence.First.Span[0]
 0458                            : reader.ValueSpan[0];
 459
 0460                        ThrowHelper.ThrowJsonReaderException(
 0461                            ref reader,
 0462                            ExceptionResource.ExpectedStartOfValueNotFound,
 0463                            displayByte);
 464
 465                        break;
 466                }
 0467            }
 0468            catch (JsonReaderException ex)
 0469            {
 470                // Re-throw with Path information.
 0471                ThrowHelper.ReThrowWithPath(ref state, ex);
 472            }
 473
 0474            Debug.Assert(!valueSpan.IsEmpty ^ !valueSequence.IsEmpty);
 0475            Debug.Assert(lineNumber >= 0);
 0476            Debug.Assert(bytePositionInLine >= 0);
 477
 478            // Carry only the position information and reader options to the scoped reader
 479            // so that any JsonException it raises reports a position relative to the original input.
 0480            var scopedCurrentState = new JsonReaderState
 0481            (
 0482                lineNumber: lineNumber,
 0483                bytePositionInLine: bytePositionInLine,
 0484                inObject: default,
 0485                isNotPrimitive: default,
 0486                valueIsEscaped: default,
 0487                trailingCommaBeforeComment: default,
 0488                tokenType: default,
 0489                previousTokenType: default,
 0490                readerOptions: reader.CurrentState.Options,
 0491                bitStack: default
 0492            );
 493
 0494            return valueSpan.IsEmpty
 0495                ? new Utf8JsonReader(valueSequence, isFinalBlock: true, state: scopedCurrentState)
 0496                : new Utf8JsonReader(valueSpan, isFinalBlock: true, state: scopedCurrentState);
 0497        }
 498    }
 499}
 500

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Serialization;
 7using System.Text.Json.Serialization.Metadata;
 8
 9namespace System.Text.Json
 10{
 11    public static partial class JsonSerializer
 12    {
 13        /// <summary>
 14        /// Converts the provided value into a <see cref="byte"/> array.
 15        /// </summary>
 16        /// <returns>A UTF-8 representation of the value.</returns>
 17        /// <param name="value">The value to convert.</param>
 18        /// <param name="options">Options to control the conversion behavior.</param>
 19        /// <exception cref="NotSupportedException">
 20        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 21        /// for <typeparamref name="TValue"/> or its serializable members.
 22        /// </exception>
 23        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 24        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 25        public static byte[] SerializeToUtf8Bytes<TValue>(
 26            TValue value,
 27            JsonSerializerOptions? options = null)
 028        {
 029            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 030            return WriteBytes(value, jsonTypeInfo);
 031        }
 32
 33        /// <summary>
 34        /// Converts the provided value into a <see cref="byte"/> array.
 35        /// </summary>
 36        /// <returns>A UTF-8 representation of the value.</returns>
 37        /// <param name="value">The value to convert.</param>
 38        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 39        /// <param name="options">Options to control the conversion behavior.</param>
 40        /// <exception cref="ArgumentException">
 41        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 42        /// </exception>
 43        /// <exception cref="System.ArgumentNullException">
 44        /// <paramref name="inputType"/> is <see langword="null"/>.
 45        /// </exception>
 46        /// <exception cref="NotSupportedException">
 47        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 48        /// for <paramref name="inputType"/>  or its serializable members.
 49        /// </exception>
 50        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 51        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 52        public static byte[] SerializeToUtf8Bytes(
 53            object? value,
 54            Type inputType,
 55            JsonSerializerOptions? options = null)
 056        {
 057            ValidateInputType(value, inputType);
 058            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 059            return WriteBytesAsObject(value, jsonTypeInfo);
 060        }
 61
 62        /// <summary>
 63        /// Converts the provided value into a <see cref="byte"/> array.
 64        /// </summary>
 65        /// <returns>A UTF-8 representation of the value.</returns>
 66        /// <param name="value">The value to convert.</param>
 67        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 68        /// <exception cref="ArgumentNullException">
 69        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 70        /// </exception>
 71        public static byte[] SerializeToUtf8Bytes<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 072        {
 073            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 74
 075            jsonTypeInfo.EnsureConfigured();
 076            return WriteBytes(value, jsonTypeInfo);
 077        }
 78
 79        /// <summary>
 80        /// Converts the provided value into a <see cref="byte"/> array.
 81        /// </summary>
 82        /// <returns>A UTF-8 representation of the value.</returns>
 83        /// <param name="value">The value to convert.</param>
 84        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 85        /// <exception cref="ArgumentNullException">
 86        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 87        /// </exception>
 88        /// <exception cref="InvalidCastException">
 89        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 90        /// </exception>
 91        public static byte[] SerializeToUtf8Bytes(object? value, JsonTypeInfo jsonTypeInfo)
 092        {
 093            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 94
 095            jsonTypeInfo.EnsureConfigured();
 096            return WriteBytesAsObject(value, jsonTypeInfo);
 097        }
 98
 99        /// <summary>
 100        /// Converts the provided value into a <see cref="byte"/> array.
 101        /// </summary>
 102        /// <returns>A UTF-8 representation of the value.</returns>
 103        /// <param name="value">The value to convert.</param>
 104        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 105        /// <param name="context">A metadata provider for serializable types.</param>
 106        /// <exception cref="ArgumentException">
 107        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 108        /// </exception>
 109        /// <exception cref="System.ArgumentNullException">
 110        /// <paramref name="inputType"/> is <see langword="null"/>.
 111        /// </exception>
 112        /// <exception cref="NotSupportedException">
 113        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 114        /// for <paramref name="inputType"/>  or its serializable members.
 115        /// </exception>
 116        /// <exception cref="InvalidOperationException">
 117        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 118        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 119        /// </exception>
 120        public static byte[] SerializeToUtf8Bytes(object? value, Type inputType, JsonSerializerContext context)
 0121        {
 0122            ArgumentNullException.ThrowIfNull(context);
 123
 0124            ValidateInputType(value, inputType);
 0125            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 0126            return WriteBytesAsObject(value, jsonTypeInfo);
 0127        }
 128
 129        private static byte[] WriteBytes<TValue>(in TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 0130        {
 0131            Debug.Assert(jsonTypeInfo.IsConfigured);
 132
 0133            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 134
 135            try
 0136            {
 0137                jsonTypeInfo.Serialize(writer, value);
 0138                return output.WrittenSpan.ToArray();
 139            }
 140            finally
 0141            {
 0142                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0143            }
 0144        }
 145
 146        private static byte[] WriteBytesAsObject(object? value, JsonTypeInfo jsonTypeInfo)
 0147        {
 0148            Debug.Assert(jsonTypeInfo.IsConfigured);
 149
 0150            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 151
 152            try
 0153            {
 0154                jsonTypeInfo.SerializeAsObject(writer, value);
 0155                return output.WrittenSpan.ToArray();
 156            }
 157            finally
 0158            {
 0159                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0160            }
 0161        }
 162    }
 163}
 164

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Serialization;
 7using System.Text.Json.Serialization.Metadata;
 8
 9namespace System.Text.Json
 10{
 11    public static partial class JsonSerializer
 12    {
 13        /// <summary>
 14        /// Converts the provided value into a <see cref="JsonDocument"/>.
 15        /// </summary>
 16        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 17        /// <returns>A <see cref="JsonDocument"/> representation of the JSON value.</returns>
 18        /// <param name="value">The value to convert.</param>
 19        /// <param name="options">Options to control the conversion behavior.</param>
 20        /// <exception cref="NotSupportedException">
 21        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 22        /// for <typeparamref name="TValue"/> or its serializable members.
 23        /// </exception>
 24        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 25        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 26        public static JsonDocument SerializeToDocument<TValue>(TValue value, JsonSerializerOptions? options = null)
 027        {
 028            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 029            return WriteDocument(value, jsonTypeInfo);
 030        }
 31
 32        /// <summary>
 33        /// Converts the provided value into a <see cref="JsonDocument"/>.
 34        /// </summary>
 35        /// <returns>A <see cref="JsonDocument"/> representation of the value.</returns>
 36        /// <param name="value">The value to convert.</param>
 37        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 38        /// <param name="options">Options to control the conversion behavior.</param>
 39        /// <exception cref="ArgumentException">
 40        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 41        /// </exception>
 42        /// <exception cref="NotSupportedException">
 43        /// <exception cref="ArgumentNullException">
 44        /// <paramref name="inputType"/> is <see langword="null"/>.
 45        /// </exception>
 46        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 47        /// for <paramref name="inputType"/>  or its serializable members.
 48        /// </exception>
 49        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 50        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 51        public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerOptions? options = n
 052        {
 053            ValidateInputType(value, inputType);
 054            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 055            return WriteDocumentAsObject(value, jsonTypeInfo);
 056        }
 57
 58        /// <summary>
 59        /// Converts the provided value into a <see cref="JsonDocument"/>.
 60        /// </summary>
 61        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 62        /// <returns>A <see cref="JsonDocument"/> representation of the value.</returns>
 63        /// <param name="value">The value to convert.</param>
 64        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 65        /// <exception cref="ArgumentNullException">
 66        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 67        /// </exception>
 68        public static JsonDocument SerializeToDocument<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 069        {
 070            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 71
 072            jsonTypeInfo.EnsureConfigured();
 073            return WriteDocument(value, jsonTypeInfo);
 074        }
 75
 76        /// <summary>
 77        /// Converts the provided value into a <see cref="JsonDocument"/>.
 78        /// </summary>
 79        /// <returns>A <see cref="JsonDocument"/> representation of the value.</returns>
 80        /// <param name="value">The value to convert.</param>
 81        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 82        /// <exception cref="ArgumentNullException">
 83        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 84        /// </exception>
 85        /// <exception cref="InvalidCastException">
 86        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 87        /// </exception>
 88        public static JsonDocument SerializeToDocument(object? value, JsonTypeInfo jsonTypeInfo)
 089        {
 090            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 91
 092            jsonTypeInfo.EnsureConfigured();
 093            return WriteDocumentAsObject(value, jsonTypeInfo);
 094        }
 95
 96        /// <summary>
 97        /// Converts the provided value into a <see cref="JsonDocument"/>.
 98        /// </summary>
 99        /// <returns>A <see cref="JsonDocument"/> representation of the value.</returns>
 100        /// <param name="value">The value to convert.</param>
 101        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 102        /// <param name="context">A metadata provider for serializable types.</param>
 103        /// <exception cref="NotSupportedException">
 104        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 105        /// for <paramref name="inputType"/> or its serializable members.
 106        /// </exception>
 107        /// <exception cref="InvalidOperationException">
 108        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 109        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 110        /// </exception>
 111        /// <exception cref="ArgumentNullException">
 112        /// <paramref name="inputType"/> or <paramref name="context"/> is <see langword="null"/>.
 113        /// </exception>
 114        public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerContext context)
 0115        {
 0116            ArgumentNullException.ThrowIfNull(context);
 117
 0118            ValidateInputType(value, inputType);
 0119            return WriteDocumentAsObject(value, GetTypeInfo(context, inputType));
 0120        }
 121
 122        private static JsonDocument WriteDocument<TValue>(in TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 0123        {
 0124            Debug.Assert(jsonTypeInfo.IsConfigured);
 0125            JsonSerializerOptions options = jsonTypeInfo.Options;
 126
 127            // For performance, share the same buffer across serialization and deserialization.
 128            // The PooledByteBufferWriter is cleared and returned when JsonDocument.Dispose() is called.
 0129            PooledByteBufferWriter output = new(options.DefaultBufferSize);
 0130            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriter(options, output);
 131
 132            try
 0133            {
 0134                jsonTypeInfo.Serialize(writer, value);
 0135                return JsonDocument.ParseRented(output, options.GetDocumentOptions());
 136            }
 137            finally
 0138            {
 0139                Utf8JsonWriterCache.ReturnWriter(writer);
 0140            }
 0141        }
 142
 143        private static JsonDocument WriteDocumentAsObject(object? value, JsonTypeInfo jsonTypeInfo)
 0144        {
 0145            Debug.Assert(jsonTypeInfo.IsConfigured);
 0146            JsonSerializerOptions options = jsonTypeInfo.Options;
 147
 148            // For performance, share the same buffer across serialization and deserialization.
 149            // The PooledByteBufferWriter is cleared and returned when JsonDocument.Dispose() is called.
 0150            PooledByteBufferWriter output = new(options.DefaultBufferSize);
 0151            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriter(options, output);
 152
 153            try
 0154            {
 0155                jsonTypeInfo.SerializeAsObject(writer, value);
 0156                return JsonDocument.ParseRented(output, options.GetDocumentOptions());
 157            }
 158            finally
 0159            {
 0160                Utf8JsonWriterCache.ReturnWriter(writer);
 0161            }
 0162        }
 163    }
 164}
 165

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Serialization;
 7using System.Text.Json.Serialization.Metadata;
 8
 9namespace System.Text.Json
 10{
 11    public static partial class JsonSerializer
 12    {
 13        /// <summary>
 14        /// Converts the provided value into a <see cref="JsonElement"/>.
 15        /// </summary>
 16        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 17        /// <returns>A <see cref="JsonElement"/> representation of the JSON value.</returns>
 18        /// <param name="value">The value to convert.</param>
 19        /// <param name="options">Options to control the conversion behavior.</param>
 20        /// <exception cref="NotSupportedException">
 21        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 22        /// for <typeparamref name="TValue"/> or its serializable members.
 23        /// </exception>
 24        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 25        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 26        public static JsonElement SerializeToElement<TValue>(TValue value, JsonSerializerOptions? options = null)
 027        {
 028            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 029            return WriteElement(value, jsonTypeInfo);
 030        }
 31
 32        /// <summary>
 33        /// Converts the provided value into a <see cref="JsonElement"/>.
 34        /// </summary>
 35        /// <returns>A <see cref="JsonElement"/> representation of the value.</returns>
 36        /// <param name="value">The value to convert.</param>
 37        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 38        /// <param name="options">Options to control the conversion behavior.</param>
 39        /// <exception cref="ArgumentException">
 40        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 41        /// </exception>
 42        /// <exception cref="NotSupportedException">
 43        /// <exception cref="ArgumentNullException">
 44        /// <paramref name="inputType"/> is <see langword="null"/>.
 45        /// </exception>
 46        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 47        /// for <paramref name="inputType"/>  or its serializable members.
 48        /// </exception>
 49        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 50        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 51        public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerOptions? options = nul
 052        {
 053            ValidateInputType(value, inputType);
 054            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 055            return WriteElementAsObject(value, jsonTypeInfo);
 056        }
 57
 58        /// <summary>
 59        /// Converts the provided value into a <see cref="JsonElement"/>.
 60        /// </summary>
 61        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 62        /// <returns>A <see cref="JsonElement"/> representation of the value.</returns>
 63        /// <param name="value">The value to convert.</param>
 64        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 65        /// <exception cref="ArgumentNullException">
 66        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 67        /// </exception>
 68        public static JsonElement SerializeToElement<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 069        {
 070            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 71
 072            jsonTypeInfo.EnsureConfigured();
 073            return WriteElement(value, jsonTypeInfo);
 074        }
 75
 76        /// <summary>
 77        /// Converts the provided value into a <see cref="JsonElement"/>.
 78        /// </summary>
 79        /// <returns>A <see cref="JsonElement"/> representation of the value.</returns>
 80        /// <param name="value">The value to convert.</param>
 81        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 82        /// <exception cref="ArgumentNullException">
 83        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 84        /// </exception>
 85        /// <exception cref="InvalidCastException">
 86        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 87        /// </exception>
 88        public static JsonElement SerializeToElement(object? value, JsonTypeInfo jsonTypeInfo)
 089        {
 090            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 91
 092            jsonTypeInfo.EnsureConfigured();
 093            return WriteElementAsObject(value, jsonTypeInfo);
 094        }
 95
 96        /// <summary>
 97        /// Converts the provided value into a <see cref="JsonElement"/>.
 98        /// </summary>
 99        /// <returns>A <see cref="JsonElement"/> representation of the value.</returns>
 100        /// <param name="value">The value to convert.</param>
 101        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 102        /// <param name="context">A metadata provider for serializable types.</param>
 103        /// <exception cref="NotSupportedException">
 104        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 105        /// for <paramref name="inputType"/> or its serializable members.
 106        /// </exception>
 107        /// <exception cref="InvalidOperationException">
 108        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 109        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 110        /// </exception>
 111        /// <exception cref="ArgumentNullException">
 112        /// <paramref name="inputType"/> or <paramref name="context"/> is <see langword="null"/>.
 113        /// </exception>
 114        public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerContext context)
 0115        {
 0116            ArgumentNullException.ThrowIfNull(context);
 117
 0118            ValidateInputType(value, inputType);
 0119            JsonTypeInfo typeInfo = GetTypeInfo(context, inputType);
 0120            return WriteElementAsObject(value, typeInfo);
 0121        }
 122
 123        private static JsonElement WriteElement<TValue>(in TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 0124        {
 0125            Debug.Assert(jsonTypeInfo.IsConfigured);
 0126            JsonSerializerOptions options = jsonTypeInfo.Options;
 127
 0128            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 129
 130            try
 0131            {
 0132                jsonTypeInfo.Serialize(writer, value);
 0133                return JsonElement.Parse(output.WrittenSpan, options.GetDocumentOptions());
 134            }
 135            finally
 0136            {
 0137                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0138            }
 0139        }
 140
 141        private static JsonElement WriteElementAsObject(object? value, JsonTypeInfo jsonTypeInfo)
 0142        {
 0143            JsonSerializerOptions options = jsonTypeInfo.Options;
 0144            Debug.Assert(options is not null);
 145
 0146            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 147
 148            try
 0149            {
 0150                jsonTypeInfo.SerializeAsObject(writer, value);
 0151                return JsonElement.Parse(output.WrittenSpan, options.GetDocumentOptions());
 152            }
 153            finally
 0154            {
 0155                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0156            }
 0157        }
 158    }
 159}
 160

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.HandleMetadata.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Text.Json.Serialization;
 6
 7namespace System.Text.Json
 8{
 9    public static partial class JsonSerializer
 10    {
 11        // Pre-encoded metadata properties.
 012        internal static readonly JsonEncodedText s_metadataId = JsonEncodedText.Encode(IdPropertyName, encoder: null);
 013        internal static readonly JsonEncodedText s_metadataRef = JsonEncodedText.Encode(RefPropertyName, encoder: null);
 014        internal static readonly JsonEncodedText s_metadataType = JsonEncodedText.Encode(TypePropertyName, encoder: null
 015        internal static readonly JsonEncodedText s_metadataValues = JsonEncodedText.Encode(ValuesPropertyName, encoder: 
 16
 17        internal static MetadataPropertyName WriteMetadataForObject(
 18            JsonConverter jsonConverter,
 19            ref WriteStack state,
 20            Utf8JsonWriter writer)
 021        {
 022            Debug.Assert(jsonConverter.CanHaveMetadata);
 023            Debug.Assert(!state.IsContinuation);
 024            Debug.Assert(state.CurrentContainsMetadata);
 25
 026            MetadataPropertyName writtenMetadata = MetadataPropertyName.None;
 27
 028            if (state.NewReferenceId is not null)
 029            {
 030                writer.WriteString(s_metadataId, state.NewReferenceId);
 031                writtenMetadata |= MetadataPropertyName.Id;
 032                state.NewReferenceId = null;
 033            }
 34
 035            if (state.PolymorphicTypeDiscriminator is object discriminator)
 036            {
 037                Debug.Assert(state.PolymorphicTypeResolver is not null);
 38
 039                JsonEncodedText propertyName =
 040                    state.PolymorphicTypeResolver.CustomTypeDiscriminatorPropertyNameJsonEncoded is JsonEncodedText cust
 041                    ? customPropertyName
 042                    : s_metadataType;
 43
 044                if (discriminator is string stringId)
 045                {
 046                    writer.WriteString(propertyName, stringId);
 047                }
 48                else
 049                {
 050                    Debug.Assert(discriminator is int);
 051                    writer.WriteNumber(propertyName, (int)discriminator);
 052                }
 53
 054                writtenMetadata |= MetadataPropertyName.Type;
 055                state.PolymorphicTypeDiscriminator = null;
 056            }
 57
 058            Debug.Assert(writtenMetadata != MetadataPropertyName.None);
 059            return writtenMetadata;
 060        }
 61
 62        internal static MetadataPropertyName WriteMetadataForCollection(
 63            JsonConverter jsonConverter,
 64            ref WriteStack state,
 65            Utf8JsonWriter writer)
 066        {
 67            // For collections with metadata, we nest the array payload within a JSON object.
 068            writer.WriteStartObject();
 069            MetadataPropertyName writtenMetadata = WriteMetadataForObject(jsonConverter, ref state, writer);
 070            writer.WritePropertyName(s_metadataValues); // property name containing nested array values.
 071            return writtenMetadata;
 072        }
 73
 74        /// <summary>
 75        /// Compute reference id for the next value to be serialized.
 76        /// </summary>
 77        internal static bool TryGetReferenceForValue(object currentValue, ref WriteStack state, Utf8JsonWriter writer)
 078        {
 079            Debug.Assert(state.NewReferenceId is null);
 80
 081            string referenceId = state.ReferenceResolver.GetReference(currentValue, out bool alreadyExists);
 082            Debug.Assert(referenceId is not null);
 83
 084            if (alreadyExists)
 085            {
 86                // Instance already serialized, write as { "$ref" : "referenceId" }
 087                writer.WriteStartObject();
 088                writer.WriteString(s_metadataRef, referenceId);
 089                writer.WriteEndObject();
 90
 91                // clear out any polymorphism state.
 092                state.PolymorphicTypeDiscriminator = null;
 093                state.PolymorphicTypeResolver = null;
 094            }
 95            else
 096            {
 97                // New instance, store computed reference id in the state
 098                state.NewReferenceId = referenceId;
 099            }
 100
 0101            return alreadyExists;
 0102        }
 103    }
 104}
 105

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Nodes;
 7using System.Text.Json.Serialization;
 8using System.Text.Json.Serialization.Metadata;
 9
 10namespace System.Text.Json
 11{
 12    public static partial class JsonSerializer
 13    {
 14        /// <summary>
 15        /// Converts the provided value into a <see cref="JsonNode"/>.
 16        /// </summary>
 17        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 18        /// <returns>A <see cref="JsonNode"/> representation of the JSON value.</returns>
 19        /// <param name="value">The value to convert.</param>
 20        /// <param name="options">Options to control the conversion behavior.</param>
 21        /// <exception cref="NotSupportedException">
 22        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 23        /// for <typeparamref name="TValue"/> or its serializable members.
 24        /// </exception>
 25        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 26        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 27        public static JsonNode? SerializeToNode<TValue>(TValue value, JsonSerializerOptions? options = null)
 028        {
 029            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 030            return WriteNode(value, jsonTypeInfo);
 031        }
 32
 33        /// <summary>
 34        /// Converts the provided value into a <see cref="JsonNode"/>.
 35        /// </summary>
 36        /// <returns>A <see cref="JsonNode"/> representation of the value.</returns>
 37        /// <param name="value">The value to convert.</param>
 38        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 39        /// <param name="options">Options to control the conversion behavior.</param>
 40        /// <exception cref="ArgumentException">
 41        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 42        /// </exception>
 43        /// <exception cref="NotSupportedException">
 44        /// <exception cref="ArgumentNullException">
 45        /// <paramref name="inputType"/> is <see langword="null"/>.
 46        /// </exception>
 47        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 48        /// for <paramref name="inputType"/>  or its serializable members.
 49        /// </exception>
 50        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 51        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 52        public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerOptions? options = null)
 053        {
 054            ValidateInputType(value, inputType);
 055            JsonTypeInfo typeInfo = GetTypeInfo(options, inputType);
 056            return WriteNodeAsObject(value, typeInfo);
 057        }
 58
 59        /// <summary>
 60        /// Converts the provided value into a <see cref="JsonNode"/>.
 61        /// </summary>
 62        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 63        /// <returns>A <see cref="JsonNode"/> representation of the value.</returns>
 64        /// <param name="value">The value to convert.</param>
 65        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 66        /// <exception cref="ArgumentNullException">
 67        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 68        /// </exception>
 69        public static JsonNode? SerializeToNode<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 070        {
 071            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 72
 073            jsonTypeInfo.EnsureConfigured();
 074            return WriteNode(value, jsonTypeInfo);
 075        }
 76
 77        /// <summary>
 78        /// Converts the provided value into a <see cref="JsonNode"/>.
 79        /// </summary>
 80        /// <returns>A <see cref="JsonNode"/> representation of the value.</returns>
 81        /// <param name="value">The value to convert.</param>
 82        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 83        /// <exception cref="ArgumentNullException">
 84        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 85        /// </exception>
 86        /// <exception cref="InvalidCastException">
 87        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 88        /// </exception>
 89        public static JsonNode? SerializeToNode(object? value, JsonTypeInfo jsonTypeInfo)
 090        {
 091            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 92
 093            jsonTypeInfo.EnsureConfigured();
 094            return WriteNodeAsObject(value, jsonTypeInfo);
 095        }
 96
 97        /// <summary>
 98        /// Converts the provided value into a <see cref="JsonNode"/>.
 99        /// </summary>
 100        /// <returns>A <see cref="JsonNode"/> representation of the value.</returns>
 101        /// <param name="value">The value to convert.</param>
 102        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 103        /// <param name="context">A metadata provider for serializable types.</param>
 104        /// <exception cref="NotSupportedException">
 105        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 106        /// for <paramref name="inputType"/> or its serializable members.
 107        /// </exception>
 108        /// <exception cref="InvalidOperationException">
 109        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 110        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 111        /// </exception>
 112        /// <exception cref="ArgumentNullException">
 113        /// <paramref name="inputType"/> or <paramref name="context"/> is <see langword="null"/>.
 114        /// </exception>
 115        public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerContext context)
 0116        {
 0117            ArgumentNullException.ThrowIfNull(context);
 118
 0119            ValidateInputType(value, inputType);
 0120            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 0121            return WriteNodeAsObject(value, jsonTypeInfo);
 0122        }
 123
 124        private static JsonNode? WriteNode<TValue>(in TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 0125        {
 0126            Debug.Assert(jsonTypeInfo.IsConfigured);
 0127            JsonSerializerOptions options = jsonTypeInfo.Options;
 128
 0129            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 130
 131            try
 0132            {
 0133                jsonTypeInfo.Serialize(writer, value);
 0134                return JsonNode.Parse(output.WrittenSpan, options.GetNodeOptions(), options.GetDocumentOptions());
 135            }
 136            finally
 0137            {
 0138                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0139            }
 0140        }
 141
 142        private static JsonNode? WriteNodeAsObject(object? value, JsonTypeInfo jsonTypeInfo)
 0143        {
 0144            Debug.Assert(jsonTypeInfo.IsConfigured);
 0145            JsonSerializerOptions options = jsonTypeInfo.Options;
 146
 0147            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 148
 149            try
 0150            {
 0151                jsonTypeInfo.SerializeAsObject(writer, value);
 0152                return JsonNode.Parse(output.WrittenSpan, options.GetNodeOptions(), options.GetDocumentOptions());
 153            }
 154            finally
 0155            {
 0156                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0157            }
 0158        }
 159    }
 160}
 161

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.IO.Pipelines;
 8using System.Text.Json.Serialization;
 9using System.Text.Json.Serialization.Metadata;
 10using System.Threading;
 11using System.Threading.Tasks;
 12
 13namespace System.Text.Json
 14{
 15    public static partial class JsonSerializer
 16    {
 17        /// <summary>
 18        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Pipelines.Pi
 19        /// </summary>
 20        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 21        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Pipelines.PipeWriter"/> to write to.</param>
 22        /// <param name="value">The value to convert.</param>
 23        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 24        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 25        /// <returns>A task that represents the asynchronous write operation.</returns>
 26        /// <exception cref="ArgumentNullException">
 27        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 28        /// </exception>
 29        public static Task SerializeAsync<TValue>(
 30            PipeWriter utf8Json,
 31            TValue value,
 32            JsonTypeInfo<TValue> jsonTypeInfo,
 33            CancellationToken cancellationToken = default)
 034        {
 035            ArgumentNullException.ThrowIfNull(utf8Json);
 036            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 37
 038            jsonTypeInfo.EnsureConfigured();
 039            return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 040        }
 41
 42        /// <summary>
 43        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Pipelines.Pi
 44        /// </summary>
 45        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 46        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Pipelines.PipeWriter"/> to write to.</param>
 47        /// <param name="value">The value to convert.</param>
 48        /// <param name="options">Options to control the conversion behavior.</param>
 49        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 50        /// <returns>A task that represents the asynchronous write operation.</returns>
 51        /// <exception cref="ArgumentNullException">
 52        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 53        /// </exception>
 54        /// <exception cref="NotSupportedException">
 55        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 56        /// for <typeparamref name="TValue"/> or its serializable members.
 57        /// </exception>
 58        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 59        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 60        public static Task SerializeAsync<TValue>(
 61            PipeWriter utf8Json,
 62            TValue value,
 63            JsonSerializerOptions? options = null,
 64            CancellationToken cancellationToken = default)
 065        {
 066            ArgumentNullException.ThrowIfNull(utf8Json);
 67
 068            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 069            return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 070        }
 71
 72        /// <summary>
 73        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Pipelines.Pi
 74        /// </summary>
 75        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Pipelines.PipeWriter"/> to write to.</param>
 76        /// <param name="value">The value to convert.</param>
 77        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 78        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 79        /// <returns>A task that represents the asynchronous write operation.</returns>
 80        /// <exception cref="ArgumentNullException">
 81        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 82        /// </exception>
 83        /// <exception cref="InvalidCastException">
 84        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 85        /// </exception>
 86        public static Task SerializeAsync(
 87            PipeWriter utf8Json,
 88            object? value,
 89            JsonTypeInfo jsonTypeInfo,
 90            CancellationToken cancellationToken = default)
 091        {
 092            ArgumentNullException.ThrowIfNull(utf8Json);
 093            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 94
 095            jsonTypeInfo.EnsureConfigured();
 096            return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
 097        }
 98
 99        /// <summary>
 100        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Pipelines.Pi
 101        /// </summary>
 102        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Pipelines.PipeWriter"/> to write to.</param>
 103        /// <param name="value">The value to convert.</param>
 104        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 105        /// <param name="context">A metadata provider for serializable types.</param>
 106        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 107        /// <returns>A task that represents the asynchronous write operation.</returns>
 108        /// <exception cref="ArgumentException">
 109        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 110        /// </exception>
 111        /// <exception cref="ArgumentNullException">
 112        /// <paramref name="utf8Json"/>, <paramref name="inputType"/>, or <paramref name="context"/> is <see langword="n
 113        /// </exception>
 114        /// <exception cref="NotSupportedException">
 115        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 116        /// for <paramref name="inputType"/>  or its serializable members.
 117        /// </exception>
 118        public static Task SerializeAsync(
 119                PipeWriter utf8Json,
 120                object? value,
 121                Type inputType,
 122                JsonSerializerContext context,
 123                CancellationToken cancellationToken = default)
 0124        {
 0125            ArgumentNullException.ThrowIfNull(utf8Json);
 0126            ArgumentNullException.ThrowIfNull(context);
 127
 0128            ValidateInputType(value, inputType);
 0129            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 130
 0131            return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
 0132        }
 133
 134        /// <summary>
 135        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Pipelines.Pi
 136        /// </summary>
 137        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Pipelines.PipeWriter"/> to write to.</param>
 138        /// <param name="value">The value to convert.</param>
 139        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 140        /// <param name="options">Options to control the conversion behavior.</param>
 141        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 142        /// <returns>A task that represents the asynchronous write operation.</returns>
 143        /// <exception cref="ArgumentException">
 144        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 145        /// </exception>
 146        /// <exception cref="ArgumentNullException">
 147        /// <paramref name="utf8Json"/> or <paramref name="inputType"/> is <see langword="null"/>.
 148        /// </exception>
 149        /// <exception cref="NotSupportedException">
 150        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 151        /// for <paramref name="inputType"/>  or its serializable members.
 152        /// </exception>
 153        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 154        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 155        public static Task SerializeAsync(
 156                PipeWriter utf8Json,
 157                object? value,
 158                Type inputType,
 159                JsonSerializerOptions? options = null,
 160                CancellationToken cancellationToken = default)
 0161        {
 0162            ArgumentNullException.ThrowIfNull(utf8Json);
 163
 0164            ValidateInputType(value, inputType);
 0165            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 166
 0167            return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
 0168        }
 169
 170        /// <summary>
 171        /// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="PipeWriter"/>
 172        /// in a streaming manner.
 173        /// </summary>
 174        /// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
 175        /// <param name="utf8Json">The <see cref="PipeWriter"/> to write to.</param>
 176        /// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
 177        /// <param name="topLevelValues"><see langword="true"/> to serialize the elements as a sequence of newline-separ
 178        /// (a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"/> to seriali
 179        /// <param name="options">Options to control the serialization behavior.</param>
 180        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 181        /// <returns>A task that represents the asynchronous write operation.</returns>
 182        /// <exception cref="ArgumentNullException">
 183        /// <paramref name="utf8Json"/> or <paramref name="value"/> is <see langword="null"/>.
 184        /// </exception>
 185        /// <remarks>
 186        /// When <paramref name="topLevelValues"/> is <see langword="true"/>, the output conforms to the
 187        /// <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> specification: each element is serialized as a
 188        /// single-line JSON value followed by a line-feed (<c>\n</c>) terminator. The line terminator is always <c>\n</
 189        /// regardless of <see cref="JsonSerializerOptions.NewLine"/>, and <see cref="JsonSerializerOptions.WriteIndente
 190        /// is ignored so that each value is emitted on a single line.
 191        /// </remarks>
 192        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 193        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 194        public static Task SerializeAsyncEnumerable<TValue>(
 195            PipeWriter utf8Json,
 196            IAsyncEnumerable<TValue> value,
 197            bool topLevelValues = false,
 198            JsonSerializerOptions? options = null,
 199            CancellationToken cancellationToken = default)
 0200        {
 0201            ArgumentNullException.ThrowIfNull(utf8Json);
 0202            ArgumentNullException.ThrowIfNull(value);
 203
 0204            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 0205            if (topLevelValues)
 0206            {
 0207                return SerializeAsyncEnumerableAsJsonLines(utf8Json, value, jsonTypeInfo, cancellationToken);
 208            }
 209
 0210            JsonTypeInfo<IAsyncEnumerable<TValue>> collectionTypeInfo = GetOrAddIAsyncEnumerableTypeInfoForSerialize(jso
 0211            return collectionTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 0212        }
 213
 214        /// <summary>
 215        /// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="PipeWriter"/>
 216        /// in a streaming manner.
 217        /// </summary>
 218        /// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
 219        /// <param name="utf8Json">The <see cref="PipeWriter"/> to write to.</param>
 220        /// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
 221        /// <param name="jsonTypeInfo">Metadata about the type of elements to serialize.</param>
 222        /// <param name="topLevelValues"><see langword="true"/> to serialize the elements as a sequence of newline-separ
 223        /// (a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"/> to seriali
 224        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 225        /// <returns>A task that represents the asynchronous write operation.</returns>
 226        /// <exception cref="ArgumentNullException">
 227        /// <paramref name="utf8Json"/>, <paramref name="value"/>, or <paramref name="jsonTypeInfo"/> is <see langword="
 228        /// </exception>
 229        /// <remarks>
 230        /// When <paramref name="topLevelValues"/> is <see langword="true"/>, the output conforms to the
 231        /// <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> specification: each element is serialized as a
 232        /// single-line JSON value followed by a line-feed (<c>\n</c>) terminator. The line terminator is always <c>\n</
 233        /// regardless of <see cref="JsonSerializerOptions.NewLine"/>, and <see cref="JsonSerializerOptions.WriteIndente
 234        /// is ignored so that each value is emitted on a single line.
 235        /// </remarks>
 236        public static Task SerializeAsyncEnumerable<TValue>(
 237            PipeWriter utf8Json,
 238            IAsyncEnumerable<TValue> value,
 239            JsonTypeInfo<TValue> jsonTypeInfo,
 240            bool topLevelValues = false,
 241            CancellationToken cancellationToken = default)
 0242        {
 0243            ArgumentNullException.ThrowIfNull(utf8Json);
 0244            ArgumentNullException.ThrowIfNull(value);
 0245            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 246
 0247            jsonTypeInfo.EnsureConfigured();
 0248            if (topLevelValues)
 0249            {
 0250                return SerializeAsyncEnumerableAsJsonLines(utf8Json, value, jsonTypeInfo, cancellationToken);
 251            }
 252
 0253            JsonTypeInfo<IAsyncEnumerable<TValue>> collectionTypeInfo = GetOrAddIAsyncEnumerableTypeInfoForSerialize(jso
 0254            return collectionTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 0255        }
 256
 257        private static async Task SerializeAsyncEnumerableAsJsonLines<TValue>(
 258            PipeWriter utf8Json,
 259            IAsyncEnumerable<TValue> value,
 260            JsonTypeInfo<TValue> jsonTypeInfo,
 261            CancellationToken cancellationToken)
 0262        {
 0263            Debug.Assert(jsonTypeInfo.IsConfigured);
 264
 0265            JsonWriterOptions writerOptions = jsonTypeInfo.Options.GetWriterOptionsForJsonLines();
 0266            int flushThreshold = (int)(FlushThreshold * (utf8Json is PooledByteBufferWriter bufferWriter
 0267                ? bufferWriter.Capacity
 0268                : 4 * PipeOptions.Default.MinimumSegmentSize));
 0269            var writer = new Utf8JsonWriter(utf8Json, writerOptions);
 270
 271            try
 0272            {
 0273                bool first = true;
 0274                await foreach (TValue item in value.WithCancellation(cancellationToken).ConfigureAwait(false))
 0275                {
 0276                    if (!first)
 0277                    {
 0278                        writer.Reset();
 0279                    }
 280
 0281                    first = false;
 0282                    FlushResult result = await jsonTypeInfo.SerializeAsync(utf8Json, item, flushThreshold, cancellationT
 283
 0284                    if (result.IsCompleted)
 0285                    {
 0286                        break;
 287                    }
 0288                }
 0289            }
 0290            catch
 0291            {
 292                // Reset the writer in exception cases so writer.Dispose() doesn't flush a partially-written value to th
 0293                writer.Reset();
 0294                throw;
 295            }
 296            finally
 0297            {
 0298                writer.Dispose();
 0299            }
 0300        }
 301    }
 302}
 303

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs

#LineLine coverage
 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
 4using System.Collections.Generic;
 5using System.Diagnostics;
 6using System.Diagnostics.CodeAnalysis;
 7using System.IO;
 8using System.Text.Json.Serialization;
 9using System.Text.Json.Serialization.Metadata;
 10using System.Threading;
 11using System.Threading.Tasks;
 12
 13namespace System.Text.Json
 14{
 15    public static partial class JsonSerializer
 16    {
 17        // We flush the Stream when the buffer is >=90% of capacity.
 18        // This threshold is a compromise between buffer utilization and minimizing cases where the buffer
 19        // needs to be expanded\doubled because it is not large enough to write the current property or element.
 20        // We check for flush after each JSON property and element is written to the buffer.
 21        // Once the buffer is expanded to contain the largest single element\property, a 90% threshold
 22        // means the buffer may be expanded a maximum of 4 times: 1-(1/(2^4))==.9375.
 23        internal const float FlushThreshold = .90f;
 24
 25        /// <summary>
 26        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 27        /// </summary>
 28        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 29        /// <returns>A task that represents the asynchronous write operation.</returns>
 30        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 31        /// <param name="value">The value to convert.</param>
 32        /// <param name="options">Options to control the conversion behavior.</param>
 33        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 34        /// <exception cref="ArgumentNullException">
 35        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 36        /// </exception>
 37        /// <exception cref="NotSupportedException">
 38        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 39        /// for <typeparamref name="TValue"/> or its serializable members.
 40        /// </exception>
 41        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 42        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 43        public static Task SerializeAsync<TValue>(
 44            Stream utf8Json,
 45            TValue value,
 46            JsonSerializerOptions? options = null,
 47            CancellationToken cancellationToken = default)
 048        {
 049            ArgumentNullException.ThrowIfNull(utf8Json);
 50
 051            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 052            return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 053        }
 54
 55        /// <summary>
 56        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 57        /// </summary>
 58        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 59        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 60        /// <param name="value">The value to convert.</param>
 61        /// <param name="options">Options to control the conversion behavior.</param>
 62        /// <exception cref="ArgumentNullException">
 63        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 64        /// </exception>
 65        /// <exception cref="NotSupportedException">
 66        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 67        /// for <typeparamref name="TValue"/> or its serializable members.
 68        /// </exception>
 69        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 70        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 71        public static void Serialize<TValue>(
 72            Stream utf8Json,
 73            TValue value,
 74            JsonSerializerOptions? options = null)
 075        {
 076            ArgumentNullException.ThrowIfNull(utf8Json);
 77
 078            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 079            jsonTypeInfo.Serialize(utf8Json, value);
 080        }
 81
 82        /// <summary>
 83        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 84        /// </summary>
 85        /// <returns>A task that represents the asynchronous write operation.</returns>
 86        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 87        /// <param name="value">The value to convert.</param>
 88        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 89        /// <param name="options">Options to control the conversion behavior.</param>
 90        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 91        /// <exception cref="ArgumentException">
 92        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 93        /// </exception>
 94        /// <exception cref="ArgumentNullException">
 95        /// <paramref name="utf8Json"/> or <paramref name="inputType"/> is <see langword="null"/>.
 96        /// </exception>
 97        /// <exception cref="NotSupportedException">
 98        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 99        /// for <paramref name="inputType"/>  or its serializable members.
 100        /// </exception>
 101        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 102        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 103        public static Task SerializeAsync(
 104            Stream utf8Json,
 105            object? value,
 106            Type inputType,
 107            JsonSerializerOptions? options = null,
 108            CancellationToken cancellationToken = default)
 0109        {
 0110            ArgumentNullException.ThrowIfNull(utf8Json);
 111
 0112            ValidateInputType(value, inputType);
 0113            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 0114            return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
 0115        }
 116
 117        /// <summary>
 118        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 119        /// </summary>
 120        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 121        /// <param name="value">The value to convert.</param>
 122        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 123        /// <param name="options">Options to control the conversion behavior.</param>
 124        /// <exception cref="ArgumentException">
 125        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 126        /// </exception>
 127        /// <exception cref="ArgumentNullException">
 128        /// <paramref name="utf8Json"/> or <paramref name="inputType"/> is <see langword="null"/>.
 129        /// </exception>
 130        /// <exception cref="NotSupportedException">
 131        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 132        /// for <paramref name="inputType"/>  or its serializable members.
 133        /// </exception>
 134        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 135        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 136        public static void Serialize(
 137            Stream utf8Json,
 138            object? value,
 139            Type inputType,
 140            JsonSerializerOptions? options = null)
 0141        {
 0142            ArgumentNullException.ThrowIfNull(utf8Json);
 143
 0144            ValidateInputType(value, inputType);
 0145            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 0146            jsonTypeInfo.SerializeAsObject(utf8Json, value);
 0147        }
 148
 149        /// <summary>
 150        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 151        /// </summary>
 152        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 153        /// <returns>A task that represents the asynchronous write operation.</returns>
 154        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 155        /// <param name="value">The value to convert.</param>
 156        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 157        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 158        /// <exception cref="ArgumentNullException">
 159        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 160        /// </exception>
 161        public static Task SerializeAsync<TValue>(
 162            Stream utf8Json,
 163            TValue value,
 164            JsonTypeInfo<TValue> jsonTypeInfo,
 165            CancellationToken cancellationToken = default)
 0166        {
 0167            ArgumentNullException.ThrowIfNull(utf8Json);
 0168            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 169
 0170            jsonTypeInfo.EnsureConfigured();
 0171            return jsonTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 0172        }
 173
 174        /// <summary>
 175        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 176        /// </summary>
 177        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 178        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 179        /// <param name="value">The value to convert.</param>
 180        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 181        /// <exception cref="ArgumentNullException">
 182        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 183        /// </exception>
 184        public static void Serialize<TValue>(
 185            Stream utf8Json,
 186            TValue value,
 187            JsonTypeInfo<TValue> jsonTypeInfo)
 0188        {
 0189            ArgumentNullException.ThrowIfNull(utf8Json);
 0190            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 191
 0192            jsonTypeInfo.EnsureConfigured();
 0193            jsonTypeInfo.Serialize(utf8Json, value);
 0194        }
 195
 196        /// <summary>
 197        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 198        /// </summary>
 199        /// <returns>A task that represents the asynchronous write operation.</returns>
 200        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 201        /// <param name="value">The value to convert.</param>
 202        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 203        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 204        /// <exception cref="ArgumentNullException">
 205        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 206        /// </exception>
 207        /// <exception cref="InvalidCastException">
 208        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 209        /// </exception>
 210        public static Task SerializeAsync(
 211            Stream utf8Json,
 212            object? value,
 213            JsonTypeInfo jsonTypeInfo,
 214            CancellationToken cancellationToken = default)
 0215        {
 0216            ArgumentNullException.ThrowIfNull(utf8Json);
 0217            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 218
 0219            jsonTypeInfo.EnsureConfigured();
 0220            return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
 0221        }
 222
 223        /// <summary>
 224        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 225        /// </summary>
 226        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 227        /// <param name="value">The value to convert.</param>
 228        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 229        /// <exception cref="ArgumentNullException">
 230        /// <paramref name="utf8Json"/> is <see langword="null"/>.
 231        /// </exception>
 232        /// <exception cref="InvalidCastException">
 233        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 234        /// </exception>
 235        public static void Serialize(
 236            Stream utf8Json,
 237            object? value,
 238            JsonTypeInfo jsonTypeInfo)
 0239        {
 0240            ArgumentNullException.ThrowIfNull(utf8Json);
 0241            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 242
 0243            jsonTypeInfo.EnsureConfigured();
 0244            jsonTypeInfo.SerializeAsObject(utf8Json, value);
 0245        }
 246
 247        /// <summary>
 248        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 249        /// </summary>
 250        /// <returns>A task that represents the asynchronous write operation.</returns>
 251        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 252        /// <param name="value">The value to convert.</param>
 253        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 254        /// <param name="context">A metadata provider for serializable types.</param>
 255        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 256        /// <exception cref="ArgumentException">
 257        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 258        /// </exception>
 259        /// <exception cref="ArgumentNullException">
 260        /// <paramref name="utf8Json"/>, <paramref name="inputType"/>, or <paramref name="context"/> is <see langword="n
 261        /// </exception>
 262        /// <exception cref="NotSupportedException">
 263        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 264        /// for <paramref name="inputType"/>  or its serializable members.
 265        /// </exception>
 266        public static Task SerializeAsync(
 267            Stream utf8Json,
 268            object? value,
 269            Type inputType,
 270            JsonSerializerContext context,
 271            CancellationToken cancellationToken = default)
 0272        {
 0273            ArgumentNullException.ThrowIfNull(utf8Json);
 0274            ArgumentNullException.ThrowIfNull(context);
 275
 0276            ValidateInputType(value, inputType);
 0277            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 0278            return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
 0279        }
 280
 281        /// <summary>
 282        /// Converts the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 283        /// </summary>
 284        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 285        /// <param name="value">The value to convert.</param>
 286        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 287        /// <param name="context">A metadata provider for serializable types.</param>
 288        /// <exception cref="ArgumentException">
 289        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 290        /// </exception>
 291        /// <exception cref="ArgumentNullException">
 292        /// <paramref name="utf8Json"/>, <paramref name="inputType"/>, or <paramref name="context"/> is <see langword="n
 293        /// </exception>
 294        /// <exception cref="NotSupportedException">
 295        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 296        /// for <paramref name="inputType"/>  or its serializable members.
 297        /// </exception>
 298        public static void Serialize(
 299            Stream utf8Json,
 300            object? value,
 301            Type inputType,
 302            JsonSerializerContext context)
 0303        {
 0304            ArgumentNullException.ThrowIfNull(utf8Json);
 0305            ArgumentNullException.ThrowIfNull(context);
 306
 0307            ValidateInputType(value, inputType);
 0308            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 0309            jsonTypeInfo.SerializeAsObject(utf8Json, value);
 0310        }
 311
 312        /// <summary>
 313        /// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="System.IO.Stream"/>
 314        /// in a streaming manner.
 315        /// </summary>
 316        /// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
 317        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 318        /// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
 319        /// <param name="topLevelValues"><see langword="true"/> to serialize the elements as a sequence of newline-separ
 320        /// (a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"/> to seriali
 321        /// <param name="options">Options to control the serialization behavior.</param>
 322        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 323        /// <returns>A task that represents the asynchronous write operation.</returns>
 324        /// <exception cref="ArgumentNullException">
 325        /// <paramref name="utf8Json"/> or <paramref name="value"/> is <see langword="null"/>.
 326        /// </exception>
 327        /// <remarks>
 328        /// When <paramref name="topLevelValues"/> is <see langword="true"/>, the output conforms to the
 329        /// <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> specification: each element is serialized as a
 330        /// single-line JSON value followed by a line-feed (<c>\n</c>) terminator. The line terminator is always <c>\n</
 331        /// regardless of <see cref="JsonSerializerOptions.NewLine"/>, and <see cref="JsonSerializerOptions.WriteIndente
 332        /// is ignored so that each value is emitted on a single line.
 333        /// </remarks>
 334        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 335        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 336        public static Task SerializeAsyncEnumerable<TValue>(
 337            Stream utf8Json,
 338            IAsyncEnumerable<TValue> value,
 339            bool topLevelValues = false,
 340            JsonSerializerOptions? options = null,
 341            CancellationToken cancellationToken = default)
 0342        {
 0343            ArgumentNullException.ThrowIfNull(utf8Json);
 0344            ArgumentNullException.ThrowIfNull(value);
 345
 0346            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 0347            if (topLevelValues)
 0348            {
 0349                return SerializeAsyncEnumerableAsJsonLines(utf8Json, value, jsonTypeInfo, cancellationToken);
 350            }
 351
 0352            JsonTypeInfo<IAsyncEnumerable<TValue>> collectionTypeInfo = GetOrAddIAsyncEnumerableTypeInfoForSerialize(jso
 0353            return collectionTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 0354        }
 355
 356        /// <summary>
 357        /// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="System.IO.Stream"/>
 358        /// in a streaming manner.
 359        /// </summary>
 360        /// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
 361        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 362        /// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
 363        /// <param name="jsonTypeInfo">Metadata about the type of elements to serialize.</param>
 364        /// <param name="topLevelValues"><see langword="true"/> to serialize the elements as a sequence of newline-separ
 365        /// (a <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> document); <see langword="false"/> to seriali
 366        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to can
 367        /// <returns>A task that represents the asynchronous write operation.</returns>
 368        /// <exception cref="ArgumentNullException">
 369        /// <paramref name="utf8Json"/>, <paramref name="value"/>, or <paramref name="jsonTypeInfo"/> is <see langword="
 370        /// </exception>
 371        /// <remarks>
 372        /// When <paramref name="topLevelValues"/> is <see langword="true"/>, the output conforms to the
 373        /// <see href="https://jsonlines.org/">JSON Lines (JSONL)</see> specification: each element is serialized as a
 374        /// single-line JSON value followed by a line-feed (<c>\n</c>) terminator. The line terminator is always <c>\n</
 375        /// regardless of <see cref="JsonSerializerOptions.NewLine"/>, and <see cref="JsonSerializerOptions.WriteIndente
 376        /// is ignored so that each value is emitted on a single line.
 377        /// </remarks>
 378        public static Task SerializeAsyncEnumerable<TValue>(
 379            Stream utf8Json,
 380            IAsyncEnumerable<TValue> value,
 381            JsonTypeInfo<TValue> jsonTypeInfo,
 382            bool topLevelValues = false,
 383            CancellationToken cancellationToken = default)
 0384        {
 0385            ArgumentNullException.ThrowIfNull(utf8Json);
 0386            ArgumentNullException.ThrowIfNull(value);
 0387            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 388
 0389            jsonTypeInfo.EnsureConfigured();
 0390            if (topLevelValues)
 0391            {
 0392                return SerializeAsyncEnumerableAsJsonLines(utf8Json, value, jsonTypeInfo, cancellationToken);
 393            }
 394
 0395            JsonTypeInfo<IAsyncEnumerable<TValue>> collectionTypeInfo = GetOrAddIAsyncEnumerableTypeInfoForSerialize(jso
 0396            return collectionTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
 0397        }
 398
 399        private static async Task SerializeAsyncEnumerableAsJsonLines<TValue>(
 400            Stream utf8Json,
 401            IAsyncEnumerable<TValue> value,
 402            JsonTypeInfo<TValue> jsonTypeInfo,
 403            CancellationToken cancellationToken)
 0404        {
 0405            Debug.Assert(jsonTypeInfo.IsConfigured);
 406
 0407            using var bufferWriter = new PooledByteBufferWriter(jsonTypeInfo.Options.DefaultBufferSize, utf8Json);
 0408            await SerializeAsyncEnumerableAsJsonLines(bufferWriter, value, jsonTypeInfo, cancellationToken).ConfigureAwa
 0409        }
 410    }
 411}
 412

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Text.Json.Serialization;
 7using System.Text.Json.Serialization.Metadata;
 8
 9namespace System.Text.Json
 10{
 11    public static partial class JsonSerializer
 12    {
 13        /// <summary>
 14        /// Converts the provided value into a <see cref="string"/>.
 15        /// </summary>
 16        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 17        /// <returns>A <see cref="string"/> representation of the value.</returns>
 18        /// <param name="value">The value to convert.</param>
 19        /// <param name="options">Options to control the conversion behavior.</param>
 20        /// <exception cref="NotSupportedException">
 21        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 22        /// for <typeparamref name="TValue"/> or its serializable members.
 23        /// </exception>
 24        /// <remarks>Using a <see cref="string"/> is not as efficient as using UTF-8
 25        /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes{TValue}(TV
 26        /// and <see cref="SerializeAsync{TValue}(IO.Stream, TValue, JsonSerializerOptions?, Threading.CancellationToken
 27        /// </remarks>
 28        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 29        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 30        public static string Serialize<TValue>(TValue value, JsonSerializerOptions? options = null)
 031        {
 032            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 033            return WriteString(value, jsonTypeInfo);
 034        }
 35
 36        /// <summary>
 37        /// Converts the provided value into a <see cref="string"/>.
 38        /// </summary>
 39        /// <returns>A <see cref="string"/> representation of the value.</returns>
 40        /// <param name="value">The value to convert.</param>
 41        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 42        /// <param name="options">Options to control the conversion behavior.</param>
 43        /// <exception cref="ArgumentException">
 44        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 45        /// </exception>
 46        /// <exception cref="NotSupportedException">
 47        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 48        /// for <paramref name="inputType"/>  or its serializable members.
 49        /// </exception>
 50        /// <exception cref="ArgumentNullException">
 51        /// <paramref name="inputType"/> is <see langword="null"/>.
 52        /// </exception>
 53        /// <remarks>Using a <see cref="string"/> is not as efficient as using UTF-8
 54        /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes(object?, T
 55        /// and <see cref="SerializeAsync(IO.Stream, object?, Type, JsonSerializerOptions?, Threading.CancellationToken)
 56        /// </remarks>
 57        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 58        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 59        public static string Serialize(
 60            object? value,
 61            Type inputType,
 62            JsonSerializerOptions? options = null)
 063        {
 064            ValidateInputType(value, inputType);
 065            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 066            return WriteStringAsObject(value, jsonTypeInfo);
 067        }
 68
 69        /// <summary>
 70        /// Converts the provided value into a <see cref="string"/>.
 71        /// </summary>
 72        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 73        /// <returns>A <see cref="string"/> representation of the value.</returns>
 74        /// <param name="value">The value to convert.</param>
 75        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 76        /// <exception cref="ArgumentNullException">
 77        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 78        /// </exception>
 79        /// <remarks>Using a <see cref="string"/> is not as efficient as using UTF-8
 80        /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes{TValue}(TV
 81        /// and <see cref="SerializeAsync{TValue}(IO.Stream, TValue, JsonTypeInfo{TValue}, Threading.CancellationToken)"
 82        /// </remarks>
 83        public static string Serialize<TValue>(TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 084        {
 085            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 86
 087            jsonTypeInfo.EnsureConfigured();
 088            return WriteString(value, jsonTypeInfo);
 089        }
 90
 91        /// <summary>
 92        /// Converts the provided value into a <see cref="string"/>.
 93        /// </summary>
 94        /// <returns>A <see cref="string"/> representation of the value.</returns>
 95        /// <param name="value">The value to convert.</param>
 96        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 97        /// <exception cref="ArgumentNullException">
 98        /// <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 99        /// </exception>
 100        /// <exception cref="InvalidCastException">
 101        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 102        /// </exception>
 103        /// <remarks>Using a <see cref="string"/> is not as efficient as using UTF-8
 104        /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes(object?, J
 105        /// and <see cref="SerializeAsync(IO.Stream, object?, JsonTypeInfo, Threading.CancellationToken)"/>.
 106        /// </remarks>
 107        public static string Serialize(object? value, JsonTypeInfo jsonTypeInfo)
 0108        {
 0109            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 110
 0111            jsonTypeInfo.EnsureConfigured();
 0112            return WriteStringAsObject(value, jsonTypeInfo);
 0113        }
 114
 115        /// <summary>
 116        /// Converts the provided value into a <see cref="string"/>.
 117        /// </summary>
 118        /// <returns>A <see cref="string"/> representation of the value.</returns>
 119        /// <param name="value">The value to convert.</param>
 120        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 121        /// <param name="context">A metadata provider for serializable types.</param>
 122        /// <exception cref="NotSupportedException">
 123        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 124        /// for <paramref name="inputType"/> or its serializable members.
 125        /// </exception>
 126        /// <exception cref="InvalidOperationException">
 127        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 128        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 129        /// </exception>
 130        /// <exception cref="ArgumentNullException">
 131        /// <paramref name="inputType"/> or <paramref name="context"/> is <see langword="null"/>.
 132        /// </exception>
 133        /// <remarks>Using a <see cref="string"/> is not as efficient as using UTF-8
 134        /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes(object?, T
 135        /// and <see cref="SerializeAsync(IO.Stream, object?, Type, JsonSerializerContext, Threading.CancellationToken)"
 136        /// </remarks>
 137        public static string Serialize(object? value, Type inputType, JsonSerializerContext context)
 0138        {
 0139            ArgumentNullException.ThrowIfNull(context);
 140
 0141            ValidateInputType(value, inputType);
 0142            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 0143            return WriteStringAsObject(value, jsonTypeInfo);
 0144        }
 145
 146        private static string WriteString<TValue>(in TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 0147        {
 0148            Debug.Assert(jsonTypeInfo.IsConfigured);
 149
 0150            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 151
 152            try
 0153            {
 0154                jsonTypeInfo.Serialize(writer, value);
 0155                return JsonReaderHelper.TranscodeHelper(output.WrittenSpan);
 156            }
 157            finally
 0158            {
 0159                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0160            }
 0161        }
 162
 163        private static string WriteStringAsObject(object? value, JsonTypeInfo jsonTypeInfo)
 0164        {
 0165            Debug.Assert(jsonTypeInfo.IsConfigured);
 166
 0167            Utf8JsonWriter writer = Utf8JsonWriterCache.RentWriterAndBuffer(jsonTypeInfo.Options, out PooledByteBufferWr
 168
 169            try
 0170            {
 0171                jsonTypeInfo.SerializeAsObject(writer, value);
 0172                return JsonReaderHelper.TranscodeHelper(output.WrittenSpan);
 173            }
 174            finally
 0175            {
 0176                Utf8JsonWriterCache.ReturnWriterAndBuffer(writer, output);
 0177            }
 0178        }
 179    }
 180}
 181

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs

#LineLine coverage
 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
 4using System.Diagnostics.CodeAnalysis;
 5using System.Text.Json.Serialization;
 6using System.Text.Json.Serialization.Metadata;
 7
 8namespace System.Text.Json
 9{
 10    public static partial class JsonSerializer
 11    {
 12        /// <summary>
 13        /// Writes one JSON value (including objects or arrays) to the provided writer.
 14        /// </summary>
 15        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 16        /// <param name="writer">The writer to write.</param>
 17        /// <param name="value">The value to convert and write.</param>
 18        /// <param name="options">Options to control the behavior.</param>
 19        /// <exception cref="ArgumentNullException">
 20        ///   <paramref name="writer"/> is <see langword="null"/>.
 21        /// </exception>
 22        /// <exception cref="NotSupportedException">
 23        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 24        /// for <typeparamref name="TValue"/> or its serializable members.
 25        /// </exception>
 26        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 27        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 28        public static void Serialize<TValue>(
 29            Utf8JsonWriter writer,
 30            TValue value,
 31            JsonSerializerOptions? options = null)
 032        {
 033            ArgumentNullException.ThrowIfNull(writer);
 34
 035            JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
 036            jsonTypeInfo.Serialize(writer, value);
 037        }
 38
 39        /// <summary>
 40        /// Writes one JSON value (including objects or arrays) to the provided writer.
 41        /// </summary>
 42        /// <param name="writer"></param>
 43        /// <param name="value">The value to convert and write.</param>
 44        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 45        /// <param name="options">Options to control the behavior.</param>
 46        /// <exception cref="ArgumentException">
 47        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 48        /// </exception>
 49        /// <exception cref="ArgumentNullException">
 50        /// <paramref name="writer"/> or <paramref name="inputType"/> is <see langword="null"/>.
 51        /// </exception>
 52        /// <exception cref="NotSupportedException">
 53        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 54        /// for <paramref name="inputType"/> or its serializable members.
 55        /// </exception>
 56        [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
 57        [RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
 58        public static void Serialize(
 59            Utf8JsonWriter writer,
 60            object? value,
 61            Type inputType,
 62            JsonSerializerOptions? options = null)
 063        {
 064            ArgumentNullException.ThrowIfNull(writer);
 65
 066            ValidateInputType(value, inputType);
 067            JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, inputType);
 068            jsonTypeInfo.SerializeAsObject(writer, value);
 069        }
 70
 71        /// <summary>
 72        /// Writes one JSON value (including objects or arrays) to the provided writer.
 73        /// </summary>
 74        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
 75        /// <param name="writer">The writer to write.</param>
 76        /// <param name="value">The value to convert and write.</param>
 77        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 78        /// <exception cref="ArgumentNullException">
 79        ///   <paramref name="writer"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 80        /// </exception>
 81        public static void Serialize<TValue>(Utf8JsonWriter writer, TValue value, JsonTypeInfo<TValue> jsonTypeInfo)
 082        {
 083            ArgumentNullException.ThrowIfNull(writer);
 084            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 85
 086            jsonTypeInfo.EnsureConfigured();
 087            jsonTypeInfo.Serialize(writer, value);
 088        }
 89
 90        /// <summary>
 91        /// Writes one JSON value (including objects or arrays) to the provided writer.
 92        /// </summary>
 93        /// <param name="writer">The writer to write.</param>
 94        /// <param name="value">The value to convert and write.</param>
 95        /// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
 96        /// <exception cref="ArgumentNullException">
 97        ///   <paramref name="writer"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
 98        /// </exception>
 99        /// <exception cref="InvalidCastException">
 100        /// <paramref name="value"/> does not match the type of <paramref name="jsonTypeInfo"/>.
 101        /// </exception>
 102        public static void Serialize(Utf8JsonWriter writer, object? value, JsonTypeInfo jsonTypeInfo)
 0103        {
 0104            ArgumentNullException.ThrowIfNull(writer);
 0105            ArgumentNullException.ThrowIfNull(jsonTypeInfo);
 106
 0107            jsonTypeInfo.EnsureConfigured();
 0108            jsonTypeInfo.SerializeAsObject(writer, value);
 0109        }
 110
 111        /// <summary>
 112        /// Writes one JSON value (including objects or arrays) to the provided writer.
 113        /// </summary>
 114        /// <param name="writer"></param>
 115        /// <param name="value">The value to convert and write.</param>
 116        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
 117        /// <param name="context">A metadata provider for serializable types.</param>
 118        /// <exception cref="ArgumentException">
 119        /// <paramref name="inputType"/> is not compatible with <paramref name="value"/>.
 120        /// </exception>
 121        /// <exception cref="ArgumentNullException">
 122        /// <paramref name="writer"/> or <paramref name="inputType"/> is <see langword="null"/>.
 123        /// </exception>
 124        /// <exception cref="NotSupportedException">
 125        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 126        /// for <paramref name="inputType"/> or its serializable members.
 127        /// </exception>
 128        /// <exception cref="InvalidOperationException">
 129        /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method of the provided
 130        /// <paramref name="context"/> returns <see langword="null"/> for the type to convert.
 131        /// </exception>
 132        public static void Serialize(Utf8JsonWriter writer, object? value, Type inputType, JsonSerializerContext context
 0133        {
 0134            ArgumentNullException.ThrowIfNull(writer);
 0135            ArgumentNullException.ThrowIfNull(context);
 136
 0137            ValidateInputType(value, inputType);
 0138            JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
 0139            jsonTypeInfo.SerializeAsObject(writer, value);
 0140        }
 141    }
 142}
 143

Methods/Properties

IsReflectionEnabledByDefault()
.cctor()
GetTypeInfo(System.Text.Json.JsonSerializerOptions,System.Type)
GetTypeInfo(System.Text.Json.JsonSerializerOptions)
GetTypeInfo(System.Text.Json.Serialization.JsonSerializerContext,System.Type)
ValidateInputType(System.Object,System.Type)
IsValidNumberHandlingValue(System.Text.Json.Serialization.JsonNumberHandling)
IsValidCreationHandlingValue(System.Text.Json.Serialization.JsonObjectCreationHandling)
IsValidUnmappedMemberHandlingValue(System.Text.Json.Serialization.JsonUnmappedMemberHandling)
UnboxOnRead(System.Object)
ThrowUnableToCastValue(System.Object)
UnboxOnWrite(System.Object)
GetOrAddListTypeInfoForRootLevelValueMode(System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<T>)
GetOrAddListTypeInfoForArrayMode(System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<T>)
GetOrAddIAsyncEnumerableTypeInfoForSerialize(System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<T>)
Deserialize(System.Text.Json.JsonDocument,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.JsonDocument,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.JsonDocument,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.Text.Json.JsonDocument,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.Text.Json.JsonDocument,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
Deserialize(System.Text.Json.JsonElement,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.JsonElement,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.JsonElement,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.Text.Json.JsonElement,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.Text.Json.JsonElement,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
.cctor()
TryReadMetadata(System.Text.Json.Serialization.JsonConverter,System.Text.Json.Serialization.Metadata.JsonTypeInfo,System.Text.Json.Utf8JsonReader&,System.Text.Json.ReadStack&)
IsMetadataPropertyName(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.Serialization.Metadata.PolymorphicTypeResolver)
GetMetadataPropertyName(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.Serialization.Metadata.PolymorphicTypeResolver)
TryHandleReferenceFromJsonElement(System.Text.Json.Utf8JsonReader&,System.Text.Json.ReadStack&,System.Text.Json.JsonElement,System.Object&)
TryHandleReferenceFromJsonNode(System.Text.Json.Utf8JsonReader&,System.Text.Json.ReadStack&,System.Text.Json.Nodes.JsonNode,System.Object&)
ReadAsStringMetadataValue(System.Text.Json.Nodes.JsonNode)
ValidateMetadataForObjectConverter(System.Text.Json.ReadStack&)
ValidateMetadataForArrayConverter(System.Text.Json.Serialization.JsonConverter,System.Text.Json.Utf8JsonReader&,System.Text.Json.ReadStack&)
ResolveReferenceId(System.Text.Json.ReadStack&)
LookupProperty(System.Object,System.ReadOnlySpan`1<System.Byte>,System.Text.Json.ReadStack&,System.Text.Json.JsonSerializerOptions,System.Boolean&,System.Boolean)
GetPropertyName(System.Text.Json.ReadStack&,System.Text.Json.Utf8JsonReader&,System.Text.Json.JsonSerializerOptions,System.Boolean&)
CreateExtensionDataProperty(System.Object,System.Text.Json.Serialization.Metadata.JsonPropertyInfo,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.Nodes.JsonNode,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.Nodes.JsonNode,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.Nodes.JsonNode,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.Text.Json.Nodes.JsonNode,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.Text.Json.Nodes.JsonNode,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
ReadFromNode(System.Text.Json.Nodes.JsonNode,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
ReadFromNodeAsObject(System.Text.Json.Nodes.JsonNode,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
DeserializeAsync(System.IO.Pipelines.PipeReader,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
DeserializeAsync(System.IO.Pipelines.PipeReader,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Threading.CancellationToken)
DeserializeAsync(System.IO.Pipelines.PipeReader,System.Text.Json.Serialization.Metadata.JsonTypeInfo,System.Threading.CancellationToken)
DeserializeAsync(System.IO.Pipelines.PipeReader,System.Type,System.Text.Json.Serialization.JsonSerializerContext,System.Threading.CancellationToken)
DeserializeAsync(System.IO.Pipelines.PipeReader,System.Type,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Pipelines.PipeReader,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Pipelines.PipeReader,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Pipelines.PipeReader,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Boolean,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Pipelines.PipeReader,System.Boolean,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
DeserializeAsyncEnumerableCore(System.IO.Pipelines.PipeReader,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<T>,System.Boolean,System.Threading.CancellationToken)
CreateAsyncEnumerableFromArray()
Deserialize(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.JsonSerializerOptions)
Deserialize(System.ReadOnlySpan`1<System.Byte>,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.ReadOnlySpan`1<System.Byte>,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
ReadFromSpan(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Nullable`1<System.Int32>)
ReadFromSpanAsObject(System.ReadOnlySpan`1<System.Byte>,System.Text.Json.Serialization.Metadata.JsonTypeInfo,System.Nullable`1<System.Int32>)
DeserializeAsync(System.IO.Stream,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
Deserialize(System.IO.Stream,System.Text.Json.JsonSerializerOptions)
DeserializeAsync(System.IO.Stream,System.Type,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
Deserialize(System.IO.Stream,System.Type,System.Text.Json.JsonSerializerOptions)
DeserializeAsync(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Threading.CancellationToken)
DeserializeAsync(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo,System.Threading.CancellationToken)
Deserialize(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
DeserializeAsync(System.IO.Stream,System.Type,System.Text.Json.Serialization.JsonSerializerContext,System.Threading.CancellationToken)
Deserialize(System.IO.Stream,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
DeserializeAsyncEnumerable(System.IO.Stream,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Stream,System.Boolean,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Threading.CancellationToken)
DeserializeAsyncEnumerable(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Boolean,System.Threading.CancellationToken)
DeserializeAsyncEnumerableCore(System.IO.Stream,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<T>,System.Boolean,System.Threading.CancellationToken)
CreateAsyncEnumerableFromArray()
Deserialize(System.String,System.Text.Json.JsonSerializerOptions)
Deserialize(System.ReadOnlySpan`1<System.Char>,System.Text.Json.JsonSerializerOptions)
Deserialize(System.String,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.ReadOnlySpan`1<System.Char>,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.String,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.ReadOnlySpan`1<System.Char>,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.String,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.ReadOnlySpan`1<System.Char>,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.String,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
Deserialize(System.ReadOnlySpan`1<System.Char>,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
ReadFromSpan(System.ReadOnlySpan`1<System.Char>,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
ReadFromSpanAsObject(System.ReadOnlySpan`1<System.Char>,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.Text.Json.Utf8JsonReader&,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.Utf8JsonReader&,System.Type,System.Text.Json.JsonSerializerOptions)
Deserialize(System.Text.Json.Utf8JsonReader&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Deserialize(System.Text.Json.Utf8JsonReader&,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Deserialize(System.Text.Json.Utf8JsonReader&,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
Read(System.Text.Json.Utf8JsonReader&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
ReadAsObject(System.Text.Json.Utf8JsonReader&,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
GetReaderScopedToNextValue(System.Text.Json.Utf8JsonReader&,System.Text.Json.ReadStack&)
SerializeToUtf8Bytes(TValue,System.Text.Json.JsonSerializerOptions)
SerializeToUtf8Bytes(System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
SerializeToUtf8Bytes(TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
SerializeToUtf8Bytes(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeToUtf8Bytes(System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
WriteBytes(TValue&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
WriteBytesAsObject(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeToDocument(TValue,System.Text.Json.JsonSerializerOptions)
SerializeToDocument(System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
SerializeToDocument(TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
SerializeToDocument(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeToDocument(System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
WriteDocument(TValue&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
WriteDocumentAsObject(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeToElement(TValue,System.Text.Json.JsonSerializerOptions)
SerializeToElement(System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
SerializeToElement(TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
SerializeToElement(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeToElement(System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
WriteElement(TValue&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
WriteElementAsObject(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
.cctor()
WriteMetadataForObject(System.Text.Json.Serialization.JsonConverter,System.Text.Json.WriteStack&,System.Text.Json.Utf8JsonWriter)
WriteMetadataForCollection(System.Text.Json.Serialization.JsonConverter,System.Text.Json.WriteStack&,System.Text.Json.Utf8JsonWriter)
TryGetReferenceForValue(System.Object,System.Text.Json.WriteStack&,System.Text.Json.Utf8JsonWriter)
SerializeToNode(TValue,System.Text.Json.JsonSerializerOptions)
SerializeToNode(System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
SerializeToNode(TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
SerializeToNode(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeToNode(System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
WriteNode(TValue&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
WriteNodeAsObject(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeAsync(System.IO.Pipelines.PipeWriter,TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Threading.CancellationToken)
SerializeAsync(System.IO.Pipelines.PipeWriter,TValue,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
SerializeAsync(System.IO.Pipelines.PipeWriter,System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo,System.Threading.CancellationToken)
SerializeAsync(System.IO.Pipelines.PipeWriter,System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext,System.Threading.CancellationToken)
SerializeAsync(System.IO.Pipelines.PipeWriter,System.Object,System.Type,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
SerializeAsyncEnumerable(System.IO.Pipelines.PipeWriter,System.Collections.Generic.IAsyncEnumerable`1<TValue>,System.Boolean,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
SerializeAsyncEnumerable(System.IO.Pipelines.PipeWriter,System.Collections.Generic.IAsyncEnumerable`1<TValue>,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Boolean,System.Threading.CancellationToken)
SerializeAsyncEnumerableAsJsonLines()
SerializeAsync(System.IO.Stream,TValue,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
Serialize(System.IO.Stream,TValue,System.Text.Json.JsonSerializerOptions)
SerializeAsync(System.IO.Stream,System.Object,System.Type,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
Serialize(System.IO.Stream,System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
SerializeAsync(System.IO.Stream,TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Threading.CancellationToken)
Serialize(System.IO.Stream,TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
SerializeAsync(System.IO.Stream,System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo,System.Threading.CancellationToken)
Serialize(System.IO.Stream,System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
SerializeAsync(System.IO.Stream,System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext,System.Threading.CancellationToken)
Serialize(System.IO.Stream,System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
SerializeAsyncEnumerable(System.IO.Stream,System.Collections.Generic.IAsyncEnumerable`1<TValue>,System.Boolean,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)
SerializeAsyncEnumerable(System.IO.Stream,System.Collections.Generic.IAsyncEnumerable`1<TValue>,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>,System.Boolean,System.Threading.CancellationToken)
SerializeAsyncEnumerableAsJsonLines()
Serialize(TValue,System.Text.Json.JsonSerializerOptions)
Serialize(System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
Serialize(TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Serialize(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Serialize(System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)
WriteString(TValue&,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
WriteStringAsObject(System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Serialize(System.Text.Json.Utf8JsonWriter,TValue,System.Text.Json.JsonSerializerOptions)
Serialize(System.Text.Json.Utf8JsonWriter,System.Object,System.Type,System.Text.Json.JsonSerializerOptions)
Serialize(System.Text.Json.Utf8JsonWriter,TValue,System.Text.Json.Serialization.Metadata.JsonTypeInfo`1<TValue>)
Serialize(System.Text.Json.Utf8JsonWriter,System.Object,System.Text.Json.Serialization.Metadata.JsonTypeInfo)
Serialize(System.Text.Json.Utf8JsonWriter,System.Object,System.Type,System.Text.Json.Serialization.JsonSerializerContext)