Criado nova biblioteca de classes para os demais projetos referênciarem a classe "Fatura.cs" Atualização de bibliotecas.
55 lines
2.2 KiB
C#
55 lines
2.2 KiB
C#
// <copyright file="DefaultDateTimeConverter.cs" company="Smart Energia">
|
|
// Copyright (c) Smart Energia. All rights reserved.
|
|
// </copyright>
|
|
namespace Faturas
|
|
{
|
|
using System;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
/// <summary>
|
|
/// Custom JSON converter for DateTime to handle default values.
|
|
/// </summary>
|
|
public class DefaultDateTimeConverter : JsonConverter<DateTime>
|
|
{
|
|
/// <summary>
|
|
/// Reads and converts the JSON to DateTime, returning DateTime.MinValue for invalid or empty strings.
|
|
/// </summary>
|
|
/// <param name="reader">The Utf8JsonReader instance to read JSON tokens from.</param>
|
|
/// <param name="typeToConvert">The target type to convert to (expected DateTime).</param>
|
|
/// <param name="options">The serializer options that may affect parsing behavior.</param>
|
|
/// <returns>The parsed DateTime value, or DateTime.MinValue when the input is null, empty, or invalid.</returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Writes the DateTime value as a string in JSON.
|
|
/// </summary>
|
|
/// <param name="writer">The Utf8JsonWriter instance to write JSON tokens to.</param>
|
|
/// <param name="value">The DateTime value to write.</param>
|
|
/// <param name="options">The serializer options that may affect writing behavior.</param>
|
|
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"));
|
|
}
|
|
}
|
|
}
|