41 lines
1.4 KiB
C#
41 lines
1.4 KiB
C#
namespace Download_Faturas
|
|
{
|
|
using System;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
public class FloatArrayOrSingleConverter : JsonConverter<float[]>
|
|
{
|
|
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 new float[] { reader.GetSingle() };
|
|
}
|
|
else
|
|
{
|
|
throw new JsonException($"Unexpected token {reader.TokenType} when parsing a float array or single float.");
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
} |