Ejemplo n.º 1
0
 /// <summary>
 /// Convert the provided value into a <see cref="System.String"/>.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="options"></param>
 /// <typeparam name="TValue"></typeparam>
 /// <returns></returns>
 public static string ToJson <TValue>(TValue?value, JsonSerializerOptions?options = null) =>
 JsonSerializer.Serialize(value, options);
        private static object?ReadValueCore(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions?options)
        {
            if (options == null)
            {
                options = JsonSerializerOptions.s_defaultOptions;
            }

            ReadStack state = default;

            state.InitializeRoot(returnType, options);

            ReadValueCore(options, ref reader, ref state);

            return(state.Current.ReturnValue);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Sends a POST request to the specified Uri containing the values async stream serialized as NDJSON in the request body.
        /// </summary>
        /// <typeparam name="T">The type of the values in async stream to be serialized.</typeparam>
        /// <param name="client">The client used to send the request.</param>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <param name="values">The async stream of values to be serialized.</param>
        /// <param name="options">The options to control the behavior during serialization.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public static Task <HttpResponseMessage> PostAsNdjsonAsync <T>(this HttpClient client, Uri?requestUri, IAsyncEnumerable <T> values, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            NdjsonAsyncEnumerableContent <T> ndjsonAsyncEnumerableContent = new NdjsonAsyncEnumerableContent <T>(values, options);

            return(client.PostAsync(requestUri, ndjsonAsyncEnumerableContent, cancellationToken));
        }
Ejemplo n.º 4
0
 public static string Serialize(object?obj, JsonSerializerOptions?options = null) =>
 JsonSerializer.Serialize(obj, options ?? DefaultOptions());
        /// <summary>
        /// Convert the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
        /// </summary>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
        /// <param name="value">The value to convert.</param>
        /// <param name="inputType">The type of the <paramref name="value"/> to convert.</param>
        /// <param name="options">Options to control the conversion behavior.</param>
        /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the write operation.</param>
        public static Task SerializeAsync(Stream utf8Json, object?value, Type inputType, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default)
        {
            if (utf8Json == null)
            {
                throw new ArgumentNullException(nameof(utf8Json));
            }

            VerifyValueAndType(value, inputType);

            return(WriteAsyncCore(utf8Json, value, inputType, options, cancellationToken));
        }
Ejemplo n.º 6
0
        public static TValue Deserialize <[DynamicallyAccessedMembers(MembersAccessedOnRead)] TValue>(string json, JsonSerializerOptions?options = null)
        {
            if (json == null)
            {
                throw new ArgumentNullException(nameof(json));
            }

            return(Deserialize <TValue>(json, typeof(TValue), options));
        }
Ejemplo n.º 7
0
 public static T Deserialize <T>(string str, JsonSerializerOptions?options = null)
     where T : new() =>
 Deserialize <T>(str, () => new T(), options);
 private static string Serialize(object?instance, JsonSerializerOptions?options) =>
 JsonSerializer.Serialize(instance, options);
 private static object?Deserialize(string json, Type targetType, JsonSerializerOptions?options) =>
 JsonSerializer.Deserialize(json, targetType, options);
Ejemplo n.º 10
0
        /// <summary>
        /// Parse the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>.
        /// </summary>
        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
        /// <param name="utf8Json">JSON text to parse.</param>
        /// <param name="returnType">The type of the object to convert to and return.</param>
        /// <param name="options">Options to control the behavior during parsing.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="returnType"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="JsonException">
        /// Thrown when the JSON is invalid,
        /// <paramref name="returnType"/> is not compatible with the JSON,
        /// or when there is remaining data in the Stream.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
        /// for <paramref name="returnType"/> or its serializable members.
        /// </exception>
        public static object?Deserialize(ReadOnlySpan <byte> utf8Json, Type returnType, JsonSerializerOptions?options = null)
        {
            if (returnType == null)
            {
                throw new ArgumentNullException(nameof(returnType));
            }

            if (options == null)
            {
                options = JsonSerializerOptions.s_defaultOptions;
            }

            var readerState = new JsonReaderState(options.GetReaderOptions());
            var reader      = new Utf8JsonReader(utf8Json, isFinalBlock: true, readerState);

            return(ReadCore <object>(ref reader, returnType, options));
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Convert the provided value into a <see cref="string"/>.
 /// </summary>
 /// <returns>A <see cref="string"/> representation of the value.</returns>
 /// <param name="value">The value to convert.</param>
 /// <param name="options">Options to control the conversion behavior.</param>
 /// <exception cref="NotSupportedException">
 /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
 /// for <typeparamref name="TValue"/> or its serializable members.
 /// </exception>
 /// <remarks>Using a <see cref="string"/> is not as efficient as using UTF-8
 /// encoding since the implementation internally uses UTF-8. See also <see cref="SerializeToUtf8Bytes{TValue}(TValue, JsonSerializerOptions?)"/>
 /// and <see cref="SerializeAsync{TValue}(IO.Stream, TValue, JsonSerializerOptions?, Threading.CancellationToken)"/>.
 /// </remarks>
 public static string Serialize <[DynamicallyAccessedMembers(MembersAccessedOnWrite)] TValue>(TValue value, JsonSerializerOptions?options = null)
 {
     return(Write(value, GetRuntimeType(value), options));
 }
Ejemplo n.º 12
0
        public BinaryData(object?jsonSerializable, JsonSerializerOptions?options = default, Type?type = default)
        {
            type ??= jsonSerializable?.GetType() ?? typeof(object);

            _bytes = JsonSerializer.SerializeToUtf8Bytes(jsonSerializable, type, options);
        }
Ejemplo n.º 13
0
 public static BinaryData FromObjectAsJson <T>(T jsonSerializable, JsonSerializerOptions?options = default)
 {
     byte[] buffer = JsonSerializer.SerializeToUtf8Bytes(jsonSerializable, typeof(T), options);
     return(new BinaryData(buffer));
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Convert the provided value into a <see cref="System.String"/>.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="value"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static string ToJson(Type type, object?value, JsonSerializerOptions?options = null) =>
 JsonSerializer.Serialize(value, type, options);
Ejemplo n.º 15
0
        public static Task <T?> ReadFromJsonAsync <[DynamicallyAccessedMembers(JsonHelpers.DeserializationMemberTypes)] T>(this HttpContent content, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            Encoding?sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet);

            return(ReadFromJsonAsyncCore <T>(content, sourceEncoding, options, cancellationToken));
        }
 private static async Task <object?> DeleteFromJsonAsyncCore(Task <HttpResponseMessage> taskResponse, Type type, JsonSerializerOptions?options, CancellationToken cancellationToken)
 {
     using (HttpResponseMessage response = await taskResponse.ConfigureAwait(false))
     {
         response.EnsureSuccessStatusCode();
         // Nullable forgiving reason:
         // DeleteAsync will usually return Content as not-null.
         // If Content happens to be null, the extension will throw.
         return(await ReadFromJsonAsyncHelper(response.Content !, type, options, cancellationToken).ConfigureAwait(false));
     }
Ejemplo n.º 17
0
 private static async Task <T?> ReadFromJsonAsyncCore <[DynamicallyAccessedMembers(JsonHelpers.DeserializationMemberTypes)] T>(HttpContent content, Encoding?sourceEncoding, JsonSerializerOptions?options, CancellationToken cancellationToken)
 {
     using (Stream contentStream = await GetContentStream(content, sourceEncoding, cancellationToken).ConfigureAwait(false))
     {
         return(await JsonSerializer.DeserializeAsync <T>(contentStream, options ?? JsonContent.s_defaultSerializerOptions, cancellationToken).ConfigureAwait(false));
     }
 }
 static Task <object?> ReadFromJsonAsyncHelper(HttpContent content, Type type, JsonSerializerOptions?options, CancellationToken cancellationToken)
 => content.ReadFromJsonAsync(type, options, cancellationToken);
Ejemplo n.º 19
0
        /// <summary>
        /// Parse the text representing a single JSON value into a <paramref name="returnType"/>.
        /// </summary>
        /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns>
        /// <param name="json">JSON text to parse.</param>
        /// <param name="returnType">The type of the object to convert to and return.</param>
        /// <param name="options">Options to control the behavior during parsing.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="json"/> or <paramref name="returnType"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="JsonException">
        /// Thrown when the JSON is invalid,
        /// the <paramref name="returnType"/> is not compatible with the JSON,
        /// or when there is remaining data in the Stream.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/>
        /// for <paramref name="returnType"/> or its serializable members.
        /// </exception>
        /// <remarks>Using a <see cref="string"/> is not as efficient as using the
        /// UTF-8 methods since the implementation natively uses UTF-8.
        /// </remarks>
        public static object?Deserialize(string json, [DynamicallyAccessedMembers(MembersAccessedOnRead)] Type returnType, JsonSerializerOptions?options = null)
        {
            if (json == null)
            {
                throw new ArgumentNullException(nameof(json));
            }

            if (returnType == null)
            {
                throw new ArgumentNullException(nameof(returnType));
            }

            object?value = Deserialize <object?>(json, returnType, options) !;

            return(value);
        }
        public static Task <object?> DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string?requestUri, Type type, JsonSerializerOptions?options, CancellationToken cancellationToken = default)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            Task <HttpResponseMessage> taskResponse = client.DeleteAsync(requestUri, cancellationToken);

            return(DeleteFromJsonAsyncCore(taskResponse, type, options, cancellationToken));
        }
Ejemplo n.º 21
0
 public static T Deserialize <T>(string str, Func <T> ifnull, JsonSerializerOptions?options = null) =>
 JsonSerializer.Deserialize <T>(str, options ?? DefaultOptions()) ?? ifnull();
        public static Task <TValue?> DeleteFromJsonAsync <TValue>(this HttpClient client, Uri?requestUri, JsonSerializerOptions?options, CancellationToken cancellationToken = default)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            Task <HttpResponseMessage> taskResponse = client.DeleteAsync(requestUri, cancellationToken);

            return(DeleteFromJsonAsyncCore <TValue>(taskResponse, options, cancellationToken));
        }
 /// <summary>
 /// Convert the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
 /// </summary>
 /// <returns>A task that represents the asynchronous write operation.</returns>
 /// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
 /// <param name="value">The value to convert.</param>
 /// <param name="options">Options to control the conversion behavior.</param>
 /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the write operation.</param>
 public static Task SerializeAsync <TValue>(Stream utf8Json, TValue value, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default)
 {
     return(WriteAsyncCore(utf8Json, value, typeof(TValue), options, cancellationToken));
 }
Ejemplo n.º 24
0
        public static Task <object?> ReadFromJsonAsync(this HttpContent content, Type type, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            Encoding?sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet);

            return(ReadFromJsonAsyncCore(content, type, sourceEncoding, options, cancellationToken));
        }
        private static async Task WriteAsyncCore(Stream utf8Json, object?value, Type inputType, JsonSerializerOptions?options, CancellationToken cancellationToken)
        {
            if (options == null)
            {
                options = JsonSerializerOptions.s_defaultOptions;
            }

            JsonWriterOptions writerOptions = options.GetWriterOptions();

            using (var bufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize))
                using (var writer = new Utf8JsonWriter(bufferWriter, writerOptions))
                {
                    if (value == null)
                    {
                        writer.WriteNullValue();
                        writer.Flush();

                        await bufferWriter.WriteToStreamAsync(utf8Json, cancellationToken).ConfigureAwait(false);

                        return;
                    }

                    if (inputType == null)
                    {
                        inputType = value.GetType();
                    }

                    WriteStack state = default;
                    state.InitializeRoot(inputType, options, supportContinuation: true);

                    bool isFinalBlock;

                    do
                    {
                        // todo: determine best value here
                        // https://github.com/dotnet/runtime/issues/32356
                        state.FlushThreshold = (int)(bufferWriter.Capacity * .9);
                        isFinalBlock         = WriteCore(
                            writer,
                            value,
                            options,
                            ref state,
                            state.Current.JsonClassInfo !.PolicyProperty !.ConverterBase);

                        writer.Flush();

                        await bufferWriter.WriteToStreamAsync(utf8Json, cancellationToken).ConfigureAwait(false);

                        bufferWriter.Clear();
                    } while (!isFinalBlock);
                }

            // todo: verify that we do want to call FlushAsync here (or above). It seems like leaving it to the caller would be best.
        }
Ejemplo n.º 26
0
 private static async Task <object?> ReadFromJsonAsyncCore(HttpContent content, Type type, Encoding?sourceEncoding, JsonSerializerOptions?options, CancellationToken cancellationToken)
 {
     using (Stream contentStream = await GetContentStream(content, sourceEncoding, cancellationToken).ConfigureAwait(false))
     {
         return(await DeserializeAsyncHelper(contentStream, type, options ?? JsonHelpers.s_defaultSerializerOptions, cancellationToken).ConfigureAwait(false));
     }
 public static TValue Deserialize <TValue>(ref Utf8JsonReader reader, JsonSerializerOptions?options = null)
 {
     return((TValue)ReadValueCore(ref reader, typeof(TValue), options) !);
 }
Ejemplo n.º 28
0
 static ValueTask <object?> DeserializeAsyncHelper(Stream contentStream, Type returnType, JsonSerializerOptions?options, CancellationToken cancellationToken)
 => JsonSerializer.DeserializeAsync(contentStream, returnType, options, cancellationToken);
 public DefaultSourceSerializer(IElasticsearchClientSettings settings, JsonSerializerOptions?options = null) => Options =
Ejemplo n.º 30
0
        public static Task <T> DeserializeAsync <T>(this HttpResponseMessage httpResponseMessage, JsonSerializerOptions?jsonSerializerOptions = null)
        {
            if (httpResponseMessage == null)
            {
                throw new ArgumentNullException(nameof(httpResponseMessage));
            }

            return(InvokeDeserializeAsync <T>(httpResponseMessage, jsonSerializerOptions));
        }