private async Task <T> GetDataInternal <T>(ObjectSerializer serializer, bool async, CancellationToken cancellationToken = default) { Argument.AssertNotNull(serializer, nameof(serializer)); if (Data != null) { return((T)Data); } else if (SystemEventExtensions.SystemEventDeserializers.TryGetValue(EventType, out Func <JsonElement, object> systemDeserializationFunction)) { return((T)systemDeserializationFunction(SerializedData)); } else { using (MemoryStream dataStream = SerializePayloadToStream(SerializedData, cancellationToken)) { if (async) { return((T)await serializer.DeserializeAsync(dataStream, typeof(T), cancellationToken).ConfigureAwait(false)); } else { return((T)serializer.Deserialize(dataStream, typeof(T), cancellationToken)); } } } }
private async Task <T> GetDataInternal <T>(ObjectSerializer serializer, bool async, CancellationToken cancellationToken = default) { Argument.AssertNotNull(serializer, nameof(serializer)); if (Data != null) { return((T)Data); } else if (SerializedData.ValueKind != JsonValueKind.Null && SerializedData.ValueKind != JsonValueKind.Undefined) { // Try to deserialize to system event if (SystemEventTypeMappings.SystemEventDeserializers.TryGetValue(Type, out Func <JsonElement, object> systemDeserializationFunction)) { return((T)systemDeserializationFunction(SerializedData)); } else { using (MemoryStream dataStream = SerializePayloadToStream(SerializedData, cancellationToken)) { if (async) { return((T)await serializer.DeserializeAsync(dataStream, typeof(T), cancellationToken).ConfigureAwait(false)); } else { return((T)serializer.Deserialize(dataStream, typeof(T), cancellationToken)); } } } } else // Both Data and SerializedData are null { return(default);
#pragma warning disable CS1572 // Not all parameters will be used depending on feature flags /// <summary> /// Deserialize a SearchSuggestion and its model. /// </summary> /// <param name="element">A JSON element.</param> /// <param name="serializer"> /// Optional serializer that can be used to customize the serialization /// of strongly typed models. /// </param> /// <param name="options">JSON serializer options.</param> /// <param name="async">Whether to execute sync or async.</param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate notifications /// that the operation should be canceled. /// </param> /// <returns>Deserialized SearchSuggestion.</returns> internal static async Task <SearchSuggestion <T> > DeserializeAsync( JsonElement element, #if EXPERIMENTAL_SERIALIZER ObjectSerializer serializer, #endif JsonSerializerOptions options, bool async, CancellationToken cancellationToken) #pragma warning restore CS1572 { Debug.Assert(options != null); SearchSuggestion <T> suggestion = new SearchSuggestion <T>(); foreach (JsonProperty prop in element.EnumerateObject()) { if (prop.NameEquals(Constants.SearchTextKeyJson.EncodedUtf8Bytes)) { suggestion.Text = prop.Value.GetString(); break; // We only have one non-model property } } // Deserialize the model #if EXPERIMENTAL_SERIALIZER if (serializer != null) { using Stream stream = element.ToStream(); T document = async ? (T)await serializer.DeserializeAsync(stream, typeof(T)).ConfigureAwait(false) : (T)serializer.Deserialize(stream, typeof(T)); suggestion.Document = document; } else { #endif T document; if (async) { using Stream stream = element.ToStream(); document = await JsonSerializer.DeserializeAsync <T>(stream, options, cancellationToken).ConfigureAwait(false); } else { document = JsonSerializer.Deserialize <T>(element.GetRawText(), options); } suggestion.Document = document; #if EXPERIMENTAL_SERIALIZER } #endif return(suggestion); }
/// <summary> /// Reads the request using the provided <see cref="ObjectSerializer"/>. /// </summary> /// <typeparam name="T">The target type of the JSON value.</typeparam> /// <param name="request">The request to be read.</param> /// <param name="serializer">The <see cref="ObjectSerializer"/> to use for the deserialization.</param> /// <param name="cancellationToken">A token that may be used to cancel the read operation.</param> /// <returns>A <see cref="ValueTask{T}"/> representing the asynchronous operation.</returns> public static ValueTask <T?> ReadFromJsonAsync <T>(this HttpRequestData request, ObjectSerializer serializer, CancellationToken cancellationToken = default) { if (request is null) { throw new ArgumentNullException(nameof(request)); } if (serializer is null) { throw new ArgumentNullException(nameof(serializer)); } ValueTask <object?> result = serializer.DeserializeAsync(request.Body, typeof(T), cancellationToken);
private async Task <ConversionResult> GetConversionResultFromDeserialization(byte[] bytes, Type type) { try { await using (var stream = new MemoryStream(bytes)) { var deserializedObject = await _serializer.DeserializeAsync(stream, type, CancellationToken.None); return(ConversionResult.Success(deserializedObject)); } } catch (Exception ex) { return(ConversionResult.Failed(ex)); } }
private async ValueTask <T> ToObjectInternalAsync <T>( ObjectSerializer serializer, bool async, CancellationToken cancellationToken) { Argument.AssertNotNull(serializer, nameof(serializer)); if (async) { return((T)await serializer.DeserializeAsync( ToStream(), typeof(T), cancellationToken) .ConfigureAwait(false)); } else { return((T)serializer.Deserialize(ToStream(), typeof(T), cancellationToken)); } }
/// <summary> /// Converts the <see cref="BinaryData"/> to the specified type using /// the provided <see cref="ObjectSerializer"/>. /// </summary> /// <typeparam name="T">The type that the data should be /// converted to.</typeparam> /// <param name="data">The <see cref="BinaryData"/> instance to convert.</param> /// <param name="serializer">The serializer to use /// when deserializing the data.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use during deserialization.</param> ///<returns>The data converted to the specified type.</returns> public static async ValueTask <T?> ToObjectAsync <T>(this BinaryData data, ObjectSerializer serializer, CancellationToken cancellationToken = default) => (T?)await serializer.DeserializeAsync(data.ToStream(), typeof(T), cancellationToken).ConfigureAwait(false);
private async Task <EventGridEvent[]> DeserializeEventGridEventsInternal(string requestContent, bool async, CancellationToken cancellationToken = default) { List <EventGridEventInternal> egInternalEvents = new List <EventGridEventInternal>(); List <EventGridEvent> egEvents = new List <EventGridEvent>(); // Deserialize raw JSON string into separate events, deserialize event envelope properties JsonDocument requestDocument = await ParseJsonToDocument(requestContent, async, cancellationToken).ConfigureAwait(false); foreach (JsonElement property in requestDocument.RootElement.EnumerateArray()) { egInternalEvents.Add(EventGridEventInternal.DeserializeEventGridEventInternal(property)); } // Deserialize 'Data' property from JsonElement for each event foreach (EventGridEventInternal egEventInternal in egInternalEvents) { JsonElement dataElement = egEventInternal.Data; object egEventData = null; // Reserialize JsonElement to stream MemoryStream dataStream = SerializePayloadToStream(dataElement, cancellationToken); // First, let's attempt to find the mapping for the event type in the custom event mapping. if (_customEventTypeMappings.TryGetValue(egEventInternal.EventType, out Type typeOfEventData)) { if (!TryGetPrimitiveFromJsonElement(dataElement, out egEventData)) { if (async) { egEventData = await _dataSerializer.DeserializeAsync(dataStream, typeOfEventData, cancellationToken).ConfigureAwait(false); } else { egEventData = _dataSerializer.Deserialize(dataStream, typeOfEventData, cancellationToken); } } } // If a custom mapping doesn't exist, let's attempt to find the mapping for the deserialization function in the system event type mapping. else if (SystemEventTypeMappings.SystemEventDeserializers.TryGetValue(egEventInternal.EventType, out Func <JsonElement, object> systemDeserializationFunction)) { egEventData = systemDeserializationFunction(dataElement); } else { // If event data is not a primitive/string, return as BinaryData if (!TryGetPrimitiveFromJsonElement(dataElement, out egEventData)) { egEventData = BinaryData.FromStream(dataStream); } } egEvents.Add(new EventGridEvent( egEventInternal.Subject, egEventData, egEventInternal.EventType, egEventInternal.DataVersion) { Id = egEventInternal.Id, EventTime = egEventInternal.EventTime }); } return(egEvents.ToArray()); }