| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Common.Converters; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Converts integers to and from JSON strings. |
| | | 9 | | /// </summary> |
| | | 10 | | public class IntegerJsonConverter : JsonConverter<int> |
| | | 11 | | { |
| | | 12 | | /// <inheritdoc /> |
| | | 13 | | public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 14 | | { |
| | 3360 | 15 | | if (reader.TokenType == JsonTokenType.Number) |
| | 3360 | 16 | | return reader.GetInt32(); |
| | | 17 | | |
| | 0 | 18 | | if (reader.TokenType == JsonTokenType.String) |
| | | 19 | | { |
| | 0 | 20 | | var value = reader.GetString()!; |
| | 0 | 21 | | return int.Parse(value, CultureInfo.InvariantCulture); |
| | | 22 | | } |
| | | 23 | | |
| | 0 | 24 | | throw new JsonException("Expected number or string."); |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <inheritdoc /> |
| | | 28 | | public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) |
| | | 29 | | { |
| | | 30 | | // Write the integer as a JSON number. |
| | 2718 | 31 | | writer.WriteNumberValue(value); |
| | 2718 | 32 | | } |
| | | 33 | | } |