faturas_4docs/Faturas/FloatArrayOrSingleConverter.cs
Adriano Serighelli 874eabe87a Refatora e atualiza projetos para .NET 9.0
Criado nova biblioteca de classes para os demais projetos referênciarem a classe "Fatura.cs"

Atualização de bibliotecas.
2025-12-01 15:22:22 -03:00

62 lines
2.5 KiB
C#

// <copyright file="FloatArrayOrSingleConverter.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 to handle float arrays or single float values.
/// </summary>
public class FloatArrayOrSingleConverter : JsonConverter<float[]>
{
/// <summary>
/// Reads and converts the JSON to either a float array or a single float value.
/// </summary>
/// <param name="reader">The reader to read from.</param>
/// <param name="typeToConvert">The type to convert.</param>
/// <param name="options">Serialization options.</param>
/// <returns>The converted float array.</returns>
/// <exception cref="JsonException">Thrown when the JSON token is not an array or a number.</exception>
public override float[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.StartArray)
{
// Se for um array, desserializa como array de floats
return JsonSerializer.Deserialize<float[]>(ref reader, options);
}
else if (reader.TokenType == JsonTokenType.Number)
{
// Se for um único valor, cria um array com esse valor
return [reader.GetSingle()];
}
else
{
throw new JsonException($"Unexpected token {reader.TokenType} when parsing a float array or single float.");
}
}
/// <summary>
/// Writes the float array or single float value to JSON.
/// </summary>
/// <param name="writer">The writer to write to.</param>
/// <param name="value">The float array value to write.</param>
/// <param name="options">Serialization options.</param>
public override void Write(Utf8JsonWriter writer, float[] value, JsonSerializerOptions options)
{
if (value.Length == 1)
{
// Se o array tiver apenas um valor, escreve como um único número
writer.WriteNumberValue(value[0]);
}
else
{
// Se o array tiver múltiplos valores, escreve como array
JsonSerializer.Serialize(writer, value, options);
}
}
}
}