From 62a4ac5c4b5d186dcab9c4ff1206318740635e2d Mon Sep 17 00:00:00 2001 From: Serraniel Date: Wed, 1 Mar 2023 21:44:13 +0100 Subject: [PATCH] Adds new JsonConverter for special ints which can have "none" as value, too. --- src/Api/Set.cs | 2 ++ .../JsonConverter/NoneIntJsonConverter.cs | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 src/Utils/JsonConverter/NoneIntJsonConverter.cs diff --git a/src/Api/Set.cs b/src/Api/Set.cs index 5cd5c11..5c5c4f7 100644 --- a/src/Api/Set.cs +++ b/src/Api/Set.cs @@ -22,6 +22,8 @@ public class Set : EndpointObject public string? Language { get; set; } + [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] + [JsonConverter(typeof(NoneIntJsonConverter))] // set hashes in card objects sometimes have "none" as year. public int Year { get; set; } // TODO: According to documentation the property currently is not supported. diff --git a/src/Utils/JsonConverter/NoneIntJsonConverter.cs b/src/Utils/JsonConverter/NoneIntJsonConverter.cs new file mode 100644 index 0000000..a8b91c3 --- /dev/null +++ b/src/Utils/JsonConverter/NoneIntJsonConverter.cs @@ -0,0 +1,36 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace JpnCardsPokemonSdk.Utils.JsonConverter; + +internal class NoneIntJsonConverter : JsonConverter +{ + public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var valueStr = reader.GetString(); + + if (valueStr?.Equals("none", StringComparison.InvariantCultureIgnoreCase) ?? true) + return -1; + + if (int.TryParse(valueStr, out var number)) + return number; + } + else if (reader.TokenType == JsonTokenType.Number) + { + return reader.GetInt32(); + } + + return -1; + } + + public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) + { + if (value >= 0) + writer.WriteNumberValue(value); + else + writer.WriteStringValue("non"); + } +} \ No newline at end of file