| | | 1 | | using System.Dynamic; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | using Elsa.Expressions.Helpers; |
| | | 5 | | using Elsa.Http.Contexts; |
| | | 6 | | using Elsa.Workflows.Serialization.Converters; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Http.Parsers; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Reads application/json and text/json content type streams. |
| | | 12 | | /// </summary> |
| | | 13 | | public class JsonHttpContentParser : IHttpContentParser |
| | | 14 | | { |
| | | 15 | | /// <inheritdoc /> |
| | 206 | 16 | | public int Priority => 0; |
| | | 17 | | |
| | | 18 | | /// <inheritdoc /> |
| | 206 | 19 | | public bool GetSupportsContentType(HttpResponseParserContext context) => context.ContentType.Contains("json", String |
| | | 20 | | |
| | | 21 | | /// <inheritdoc /> |
| | | 22 | | public async Task<object> ReadAsync(HttpResponseParserContext context) |
| | | 23 | | { |
| | 6 | 24 | | var options = new JsonSerializerOptions |
| | 6 | 25 | | { |
| | 6 | 26 | | PropertyNameCaseInsensitive = true |
| | 6 | 27 | | }; |
| | | 28 | | |
| | 6 | 29 | | options.Converters.Add(new JsonStringEnumConverter()); |
| | | 30 | | |
| | 6 | 31 | | var content = context.Content; |
| | 6 | 32 | | using var reader = new StreamReader(content, leaveOpen: true); |
| | 6 | 33 | | var json = await reader.ReadToEndAsync(); |
| | 6 | 34 | | var returnType = context.ReturnType; |
| | | 35 | | |
| | 6 | 36 | | if(returnType == typeof(string)) |
| | 0 | 37 | | return json; |
| | | 38 | | |
| | 6 | 39 | | if (returnType == null || returnType.IsPrimitive) |
| | 0 | 40 | | return json.ConvertTo(returnType ?? typeof(string))!; |
| | | 41 | | |
| | 6 | 42 | | if (returnType != typeof(ExpandoObject) && returnType != typeof(object)) |
| | 0 | 43 | | return JsonSerializer.Deserialize(json, returnType, options)!; |
| | | 44 | | |
| | 6 | 45 | | options.Converters.Add(new ExpandoObjectConverterFactory()); |
| | 6 | 46 | | return JsonSerializer.Deserialize<object>(json, options)!; |
| | 6 | 47 | | } |
| | | 48 | | } |