using System; using System.Text.Json; using System.Text.Json.Serialization; /// /// /// public class JsonDateTimeConverter : JsonConverter { private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff tt"; /// /// Reads and converts the JSON to type. /// /// The reader. /// The type to convert. /// An object that specifies serialization options to use. /// /// The converted value. /// /// /// Unexpected token type: {reader.TokenType} /// or /// Unable to convert '{dateTimeString}' to DateTime /// public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.String) { throw new JsonException($"Unexpected token type: {reader.TokenType}"); } string dateTimeString = reader.GetString(); if (DateTime.TryParseExact(dateTimeString, DateTimeFormat, null, System.Globalization.DateTimeStyles.None, out DateTime dateTime)) { return dateTime; } else { throw new JsonException($"Unable to convert '{dateTimeString}' to DateTime"); } } /// /// Writes a specified value as JSON. /// /// The writer to write to. /// The value to convert to JSON. /// An object that specifies serialization options to use. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { string dateTimeString = value.ToString(DateTimeFormat); writer.WriteStringValue(dateTimeString); } /// /// Determines whether the specified type can be converted. /// /// The type to compare against. /// /// if the type can be converted; otherwise, . /// public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(DateTime); } }