| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Http.Serialization; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A custom JSON converter for HttpHeaders that supports both single and multiple values. |
| | | 8 | | /// </summary> |
| | | 9 | | public class HttpHeadersConverter : JsonConverter<HttpHeaders> |
| | | 10 | | { |
| | | 11 | | /// <inheritdoc /> |
| | | 12 | | public override HttpHeaders Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 13 | | { |
| | 1 | 14 | | if (reader.TokenType != JsonTokenType.StartObject) |
| | 0 | 15 | | throw new JsonException("Expected StartObject token"); |
| | | 16 | | |
| | 1 | 17 | | var headers = new HttpHeaders(); |
| | | 18 | | |
| | 1 | 19 | | while (reader.Read()) |
| | | 20 | | { |
| | 1 | 21 | | if (reader.TokenType == JsonTokenType.EndObject) |
| | 1 | 22 | | return headers; |
| | | 23 | | |
| | 0 | 24 | | if (reader.TokenType != JsonTokenType.PropertyName) |
| | 0 | 25 | | throw new JsonException("Expected a PropertyName token"); |
| | | 26 | | |
| | 0 | 27 | | var key = reader.GetString()!; |
| | 0 | 28 | | reader.Read(); |
| | | 29 | | |
| | | 30 | | // If the next token is not a StartArray token, then we expect a String token. |
| | 0 | 31 | | switch (reader.TokenType) |
| | | 32 | | { |
| | | 33 | | case JsonTokenType.StartArray: |
| | | 34 | | { |
| | 0 | 35 | | var values = new List<string>(); |
| | 0 | 36 | | while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) values.Add(reader.GetString()!); |
| | 0 | 37 | | headers.Add(key, values.ToArray()); |
| | 0 | 38 | | break; |
| | | 39 | | } |
| | | 40 | | case JsonTokenType.String: |
| | | 41 | | { |
| | 0 | 42 | | var singleValue = reader.GetString()!; |
| | 0 | 43 | | headers.Add(key, new[] { singleValue }); |
| | 0 | 44 | | break; |
| | | 45 | | } |
| | | 46 | | default: |
| | 0 | 47 | | throw new JsonException("Expected a String or StartArray token"); |
| | | 48 | | } |
| | | 49 | | } |
| | | 50 | | |
| | 0 | 51 | | throw new JsonException("Expected an EndObject token"); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <inheritdoc /> |
| | | 55 | | public override void Write(Utf8JsonWriter writer, HttpHeaders value, JsonSerializerOptions options) |
| | | 56 | | { |
| | 12 | 57 | | writer.WriteStartObject(); |
| | | 58 | | |
| | 24 | 59 | | foreach (var header in value) |
| | | 60 | | { |
| | 0 | 61 | | writer.WritePropertyName(header.Key); |
| | 0 | 62 | | writer.WriteStartArray(); |
| | 0 | 63 | | foreach (var headerValue in header.Value) writer.WriteStringValue(headerValue); |
| | 0 | 64 | | writer.WriteEndArray(); |
| | | 65 | | } |
| | | 66 | | |
| | 12 | 67 | | writer.WriteEndObject(); |
| | 12 | 68 | | } |
| | | 69 | | } |