| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Workflows.Serialization.Converters; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Converts primitives to and from JSON strings. |
| | | 9 | | /// </summary> |
| | | 10 | | public class JsonPrimitiveToStringConverter : JsonConverter<string> |
| | | 11 | | { |
| | | 12 | | /// <inheritdoc /> |
| | | 13 | | public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | | 14 | | { |
| | 1524 | 15 | | switch (reader.TokenType) |
| | | 16 | | { |
| | | 17 | | case JsonTokenType.True: |
| | 0 | 18 | | return "True"; |
| | | 19 | | case JsonTokenType.False: |
| | 0 | 20 | | return "False"; |
| | 0 | 21 | | case JsonTokenType.Number when reader.TryGetInt64(out var l): |
| | 0 | 22 | | return l.ToString(); |
| | | 23 | | case JsonTokenType.Number: |
| | 0 | 24 | | return reader.GetDouble().ToString(CultureInfo.InvariantCulture); |
| | 1524 | 25 | | case JsonTokenType.String when reader.TryGetDateTimeOffset(out var datetime): |
| | 0 | 26 | | return datetime.ToString(); |
| | | 27 | | case JsonTokenType.String: |
| | 1524 | 28 | | return reader.GetString()!; |
| | | 29 | | default: |
| | | 30 | | { |
| | | 31 | | // Use JsonElement as fallback. |
| | 0 | 32 | | using var document = JsonDocument.ParseValue(ref reader); |
| | 0 | 33 | | return document.RootElement.Clone().ToString(); |
| | | 34 | | } |
| | | 35 | | } |
| | 0 | 36 | | } |
| | | 37 | | |
| | | 38 | | /// <inheritdoc /> |
| | | 39 | | public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) |
| | | 40 | | { |
| | 0 | 41 | | writer.WriteStringValue(value); |
| | 0 | 42 | | } |
| | | 43 | | } |