//
// Copyright (c) Smart Energia. All rights reserved.
//
namespace Faturas
{
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
///
/// Custom JSON converter to handle float arrays or single float values.
///
public class FloatArrayOrSingleConverter : JsonConverter
{
///
/// Reads and converts the JSON to either a float array or a single float value.
///
/// The reader to read from.
/// The type to convert.
/// Serialization options.
/// The converted float array.
/// Thrown when the JSON token is not an array or a number.
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(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.");
}
}
///
/// Writes the float array or single float value to JSON.
///
/// The writer to write to.
/// The float array value to write.
/// Serialization options.
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);
}
}
}
}