| | | 1 | | using System; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | |
| | | 5 | | namespace SwiftCollections; |
| | | 6 | | |
| | | 7 | | public sealed class SwiftStateJsonConverter<TCollection, TState> : JsonConverter<TCollection> where TCollection : class |
| | | 8 | | { |
| | | 9 | | private readonly Func<TState, TCollection> _factory; |
| | | 10 | | private readonly Func<TCollection, TState> _stateGetter; |
| | | 11 | | |
| | 33 | 12 | | public SwiftStateJsonConverter( |
| | 33 | 13 | | Func<TState, TCollection> factory, |
| | 33 | 14 | | Func<TCollection, TState> stateGetter) |
| | 33 | 15 | | { |
| | 33 | 16 | | _factory = factory; |
| | 33 | 17 | | _stateGetter = stateGetter; |
| | 33 | 18 | | } |
| | | 19 | | |
| | | 20 | | public override TCollection Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 42 | 21 | | { |
| | 42 | 22 | | if (reader.TokenType != JsonTokenType.StartObject) |
| | 1 | 23 | | throw new JsonException(); |
| | | 24 | | |
| | 41 | 25 | | reader.Read(); |
| | | 26 | | |
| | 41 | 27 | | if (reader.TokenType != JsonTokenType.PropertyName) |
| | 1 | 28 | | throw new JsonException(); |
| | | 29 | | |
| | 40 | 30 | | if (!reader.ValueTextEquals("State")) |
| | 1 | 31 | | throw new JsonException(); |
| | | 32 | | |
| | 39 | 33 | | reader.Read(); |
| | | 34 | | |
| | 39 | 35 | | var state = JsonSerializer.Deserialize<TState>(ref reader, options); |
| | | 36 | | |
| | 39 | 37 | | if (!reader.Read() || reader.TokenType != JsonTokenType.EndObject) |
| | 1 | 38 | | throw new JsonException(); |
| | | 39 | | |
| | 38 | 40 | | return _factory(state); |
| | 38 | 41 | | } |
| | | 42 | | |
| | | 43 | | public override void Write(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options) |
| | 39 | 44 | | { |
| | 39 | 45 | | writer.WriteStartObject(); |
| | | 46 | | |
| | 39 | 47 | | var state = _stateGetter(value); |
| | | 48 | | |
| | 39 | 49 | | writer.WritePropertyName("State"); |
| | 39 | 50 | | JsonSerializer.Serialize(writer, state, options); |
| | | 51 | | |
| | 39 | 52 | | writer.WriteEndObject(); |
| | 39 | 53 | | } |
| | | 54 | | } |