Skip to content

Commit

Permalink
(GH-362) Replace DateOnly with (int Year, int Month, int Day))
Browse files Browse the repository at this point in the history
  • Loading branch information
Jericho committed Oct 13, 2024
1 parent 106f060 commit 847b0fb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
37 changes: 37 additions & 0 deletions Source/ZoomNet/Json/DateOnlyConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Text.Json;

namespace ZoomNet.Json
{
/// <summary>
/// Converts a DateOnly (which is represented by 3 integer values: year, month and day) to or from JSON.
/// </summary>
/// <seealso cref="ZoomNetJsonConverter{T}"/>
internal class DateOnlyConverter : ZoomNetJsonConverter<(int Year, int Month, int Day)>
{
public override (int Year, int Month, int Day) Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.None:
case JsonTokenType.Null:
case JsonTokenType.String when string.IsNullOrEmpty(reader.GetString()):
throw new JsonException("Unable to convert a null value to DateOnly");

case JsonTokenType.String:
var rawValue = reader.GetString();
var parts = rawValue.Split('-');
if (parts.Length != 3) throw new JsonException($"Unable to convert {rawValue} to DateOnly");
return (int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]));

default:
throw new JsonException($"Unable to convert {reader.TokenType.ToEnumString()} to DateOnly");
}
}

public override void Write(Utf8JsonWriter writer, (int Year, int Month, int Day) value, JsonSerializerOptions options)
{
writer.WriteStringValue($"{value.Year:D4}-{value.Month:D2}-{value.Day:D2}");
}
}
}
5 changes: 3 additions & 2 deletions Source/ZoomNet/Models/DailyUsageSummary.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using System.Text.Json.Serialization;
using ZoomNet.Json;

namespace ZoomNet.Models
{
Expand All @@ -10,7 +10,8 @@ public class DailyUsageSummary
{
/// <summary>Gets or sets the date.</summary>
[JsonPropertyName("date")]
public DateOnly Date { get; set; }
[JsonConverter(typeof(DateOnlyConverter))]
public (int Year, int Month, int Day) Date { get; set; }

/// <summary>Gets or sets number of meeting minutes.</summary>
[JsonPropertyName("meeting_minutes")]
Expand Down

0 comments on commit 847b0fb

Please sign in to comment.