feat: add CompactNordPoolDayPrice with array-format JSON serialization
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace NordPool.Models;
|
||||
|
||||
[JsonConverter(typeof(CompactNordPoolDayPriceConverter))]
|
||||
public readonly struct CompactNordPoolDayPrice
|
||||
{
|
||||
public long Start { get; init; }
|
||||
public long End { get; init; }
|
||||
public double? Price { get; init; }
|
||||
|
||||
public static CompactNordPoolDayPrice FromDayPrice(NordPoolDayPrice dayPrice)
|
||||
{
|
||||
return new CompactNordPoolDayPrice
|
||||
{
|
||||
Start = dayPrice.Start.HasValue
|
||||
? new DateTimeOffset(dayPrice.Start.Value, TimeSpan.Zero).ToUnixTimeSeconds()
|
||||
: 0L,
|
||||
End = dayPrice.End.HasValue
|
||||
? new DateTimeOffset(dayPrice.End.Value, TimeSpan.Zero).ToUnixTimeSeconds()
|
||||
: 0L,
|
||||
Price = dayPrice.Price
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNordPoolDayPrice>
|
||||
{
|
||||
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.StartArray)
|
||||
throw new JsonException("Expected start of array.");
|
||||
|
||||
reader.Read();
|
||||
var start = reader.GetInt64();
|
||||
|
||||
reader.Read();
|
||||
var end = reader.GetInt64();
|
||||
|
||||
reader.Read();
|
||||
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
|
||||
|
||||
reader.Read();
|
||||
if (reader.TokenType != JsonTokenType.EndArray)
|
||||
throw new JsonException("Expected end of array.");
|
||||
|
||||
return new CompactNordPoolDayPrice { Start = start, End = end, Price = price };
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, CompactNordPoolDayPrice value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStartArray();
|
||||
writer.WriteNumberValue(value.Start);
|
||||
writer.WriteNumberValue(value.End);
|
||||
|
||||
if (value.Price.HasValue)
|
||||
writer.WriteNumberValue(value.Price.Value);
|
||||
else
|
||||
writer.WriteNullValue();
|
||||
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user