2023-01-16 18:42:45 +00:00
|
|
|
using System.Dynamic;
|
|
|
|
|
using System.Text.Json;
|
2023-01-31 11:40:50 +00:00
|
|
|
using System.Text.Json.Serialization;
|
2023-01-16 18:42:45 +00:00
|
|
|
using Elsa.Expressions.Helpers;
|
2023-03-03 21:47:23 +00:00
|
|
|
using Elsa.Http.Contracts;
|
2023-01-16 18:42:45 +00:00
|
|
|
using Elsa.Workflows.Core.Serialization.Converters;
|
|
|
|
|
|
|
|
|
|
namespace Elsa.Http.Parsers;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Reads application/json and text/json content type streams.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class JsonHttpContentParser : IHttpContentParser
|
|
|
|
|
{
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public int Priority => 0;
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public bool GetSupportsContentType(string contentType) => contentType.Contains("json", StringComparison.InvariantCultureIgnoreCase);
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public async Task<object> ReadAsync(Stream content, Type? returnType, CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
var options = new JsonSerializerOptions
|
|
|
|
|
{
|
|
|
|
|
PropertyNameCaseInsensitive = true
|
|
|
|
|
};
|
2023-01-31 11:40:50 +00:00
|
|
|
|
|
|
|
|
options.Converters.Add(new JsonStringEnumConverter());
|
2023-01-16 18:42:45 +00:00
|
|
|
|
|
|
|
|
using var reader = new StreamReader(content, leaveOpen: true);
|
|
|
|
|
var json = await reader.ReadToEndAsync();
|
|
|
|
|
|
|
|
|
|
if (returnType == null || returnType.IsPrimitive)
|
|
|
|
|
return json.ConvertTo(returnType ?? typeof(string))!;
|
|
|
|
|
|
2023-05-10 14:10:24 +00:00
|
|
|
if (returnType != typeof(ExpandoObject) && returnType != typeof(object))
|
2023-01-16 18:42:45 +00:00
|
|
|
return JsonSerializer.Deserialize(json, returnType, options)!;
|
|
|
|
|
|
2023-05-10 11:57:44 +00:00
|
|
|
options.Converters.Add(new ExpandoObjectConverterFactory());
|
2023-01-16 18:42:45 +00:00
|
|
|
return JsonSerializer.Deserialize<object>(json, options)!;
|
|
|
|
|
}
|
|
|
|
|
}
|