// // Copyright (c) Smart Energia. All rights reserved. // namespace Faturas { using System; using System.Text.Json; using System.Text.Json.Serialization; /// /// Custom JSON converter for DateTime to handle default values. /// public class DefaultDateTimeConverter : JsonConverter { /// /// Reads and converts the JSON to DateTime, returning DateTime.MinValue for invalid or empty strings. /// /// The Utf8JsonReader instance to read JSON tokens from. /// The target type to convert to (expected DateTime). /// The serializer options that may affect parsing behavior. /// The parsed DateTime value, or DateTime.MinValue when the input is null, empty, or invalid. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { string? str = reader.GetString(); if (string.IsNullOrWhiteSpace(str)) { return DateTime.MinValue; } if (DateTime.TryParse(str, out var date)) { return date; } } return DateTime.MinValue; } /// /// Writes the DateTime value as a string in JSON. /// /// The Utf8JsonWriter instance to write JSON tokens to. /// The DateTime value to write. /// The serializer options that may affect writing behavior. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { // Write DateTime in round-trip ISO 8601 format so JSON consumers can parse it reliably. writer.WriteStringValue(value.ToString("o")); } } }