forked from elsa-workflows/elsa-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonHttpContentParser.cs
46 lines (36 loc) · 1.51 KB
/
JsonHttpContentParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Dynamic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Elsa.Expressions.Helpers;
using Elsa.Http.Contracts;
using Elsa.Workflows.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
};
options.Converters.Add(new JsonStringEnumConverter());
using var reader = new StreamReader(content, leaveOpen: true);
var json = await reader.ReadToEndAsync();
if(returnType == typeof(string))
return json;
if (returnType == null || returnType.IsPrimitive)
return json.ConvertTo(returnType ?? typeof(string))!;
if (returnType != typeof(ExpandoObject) && returnType != typeof(object))
return JsonSerializer.Deserialize(json, returnType, options)!;
options.Converters.Add(new ExpandoObjectConverterFactory());
return JsonSerializer.Deserialize<object>(json, options)!;
}
}