From a1f10da3d9bf9e066f5557f1ceeb9d49a40041d3 Mon Sep 17 00:00:00 2001 From: Serraniel Date: Fri, 24 Mar 2023 18:10:23 +0100 Subject: [PATCH] #1 Introduces additional customdatetimeconverter Required to parse the given datetime format --- JpnCardsPokemon.Sdk/Api/CardPrice.cs | 2 + .../JsonConverter/CustomDateTimeConverter.cs | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 JpnCardsPokemon.Sdk/Utils/JsonConverter/CustomDateTimeConverter.cs diff --git a/JpnCardsPokemon.Sdk/Api/CardPrice.cs b/JpnCardsPokemon.Sdk/Api/CardPrice.cs index 5402a02..d398ee4 100644 --- a/JpnCardsPokemon.Sdk/Api/CardPrice.cs +++ b/JpnCardsPokemon.Sdk/Api/CardPrice.cs @@ -1,5 +1,6 @@ using System; using System.Text.Json.Serialization; +using JpnCardsPokemon.Sdk.Utils.JsonConverter; namespace JpnCardsPokemon.Sdk.Api; @@ -38,6 +39,7 @@ public class CardPrice /// Date when the price information was updated last. /// [JsonPropertyName("dateUpdated")] + [JsonConverter(typeof(CustomDateTimeConverter))] public DateTime? UpdatedDate { get; set; } /// diff --git a/JpnCardsPokemon.Sdk/Utils/JsonConverter/CustomDateTimeConverter.cs b/JpnCardsPokemon.Sdk/Utils/JsonConverter/CustomDateTimeConverter.cs new file mode 100644 index 0000000..45c47b5 --- /dev/null +++ b/JpnCardsPokemon.Sdk/Utils/JsonConverter/CustomDateTimeConverter.cs @@ -0,0 +1,46 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace JpnCardsPokemon.Sdk.Utils.JsonConverter +{ + internal class CustomDateTimeConverter : JsonConverter + { + private readonly string _dateTimeFormat = "MM/dd/yyyy"; + + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.Null: + return null; + case JsonTokenType.String: + { + var dateString = reader.GetString(); + if (DateTime.TryParseExact(dateString, _dateTimeFormat, null, System.Globalization.DateTimeStyles.None, out var dateTime)) + { + return dateTime; + } + + break; + } + default: + throw new JsonException($"Cannot convert {reader.GetString()} to DateTime."); + } + + throw new JsonException($"Cannot convert {reader.GetString()} to DateTime."); + } + + public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) + { + if (value.HasValue) + { + writer.WriteStringValue(value.Value.ToString(_dateTimeFormat)); + } + else + { + writer.WriteNullValue(); + } + } + } +}