| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Persistence.EFCore.Converters; |
| | | 5 | | |
| | | 6 | | public class PrimitiveDictionaryConverter : JsonConverter<IDictionary<string, object>> |
| | | 7 | | { |
| | | 8 | | public override IDictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOption |
| | | 9 | | { |
| | 0 | 10 | | if (reader.TokenType != JsonTokenType.StartObject) |
| | 0 | 11 | | throw new JsonException("Expected start of object."); |
| | | 12 | | |
| | 0 | 13 | | var dictionary = new Dictionary<string, object>(); |
| | | 14 | | |
| | 0 | 15 | | while (reader.Read()) |
| | | 16 | | { |
| | 0 | 17 | | if (reader.TokenType == JsonTokenType.EndObject) |
| | 0 | 18 | | return dictionary; |
| | | 19 | | |
| | 0 | 20 | | var key = reader.GetString()!; |
| | 0 | 21 | | reader.Read(); |
| | 0 | 22 | | var value = ReadValue(ref reader, options); |
| | 0 | 23 | | dictionary.Add(key, value); |
| | | 24 | | } |
| | | 25 | | |
| | 0 | 26 | | throw new JsonException("Expected end of object."); |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | private object ReadValue(ref Utf8JsonReader reader, JsonSerializerOptions options) |
| | | 30 | | { |
| | 0 | 31 | | switch (reader.TokenType) |
| | | 32 | | { |
| | | 33 | | case JsonTokenType.String: |
| | 0 | 34 | | return reader.GetString()!; |
| | | 35 | | case JsonTokenType.Number: |
| | 0 | 36 | | if (reader.TryGetInt64(out var l)) |
| | 0 | 37 | | return l; |
| | 0 | 38 | | return reader.GetDouble(); |
| | | 39 | | case JsonTokenType.True: |
| | 0 | 40 | | return true; |
| | | 41 | | case JsonTokenType.False: |
| | 0 | 42 | | return false; |
| | | 43 | | case JsonTokenType.Null: |
| | 0 | 44 | | return null!; |
| | | 45 | | case JsonTokenType.StartObject: |
| | 0 | 46 | | return JsonSerializer.Deserialize<Dictionary<string, object>>(ref reader, options)!; |
| | | 47 | | case JsonTokenType.StartArray: |
| | 0 | 48 | | return JsonSerializer.Deserialize<List<object>>(ref reader, options)!; |
| | | 49 | | default: |
| | 0 | 50 | | using (var document = JsonDocument.ParseValue(ref reader)) |
| | | 51 | | { |
| | 0 | 52 | | return document.RootElement.Clone().ToString(); |
| | | 53 | | } |
| | | 54 | | } |
| | 0 | 55 | | } |
| | | 56 | | |
| | | 57 | | public override void Write(Utf8JsonWriter writer, IDictionary<string, object> value, JsonSerializerOptions options) |
| | | 58 | | { |
| | 0 | 59 | | writer.WriteStartObject(); |
| | | 60 | | |
| | 0 | 61 | | foreach (var kvp in value) |
| | | 62 | | { |
| | 0 | 63 | | writer.WritePropertyName(kvp.Key); |
| | 0 | 64 | | JsonSerializer.Serialize(writer, kvp.Value, options); |
| | | 65 | | } |
| | | 66 | | |
| | 0 | 67 | | writer.WriteEndObject(); |
| | 0 | 68 | | } |
| | | 69 | | } |