Skip to content

Commit

Permalink
Parse unix time values from the JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
akacdev committed Aug 24, 2024
1 parent b008c83 commit 5aaa783
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
29 changes: 29 additions & 0 deletions Certstream/JsonConverters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System;
using System.Text.Json.Serialization;
using System.Text.Json;

namespace Certstream
{
public class UnixDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
{
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number)
{
if (reader.TryGetInt64(out long longTime))
return DateTimeOffset.FromUnixTimeSeconds(longTime);

if (reader.TryGetDouble(out double doubleTime))
return DateTimeOffset.FromUnixTimeSeconds((long)doubleTime);
}

throw new JsonException("Expected a number representing Unix time.");
}

public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
long unixTime = (long)value.ToUnixTimeSeconds();
writer.WriteNumberValue(unixTime);
}
}
}
9 changes: 6 additions & 3 deletions Certstream/Models/LeafCertificate.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
using System;
using System.Text.Json.Serialization;

namespace Certstream.Models
{
Expand All @@ -16,11 +17,13 @@ public struct LeafCertificate
[JsonPropertyName("issuer")]
public Issuer Issuer { get; set; }

[JsonConverter(typeof(UnixDateTimeOffsetConverter))]
[JsonPropertyName("not_after")]
public int NotAfter { get; set; }
public DateTimeOffset NotAfter { get; set; }

[JsonConverter(typeof(UnixDateTimeOffsetConverter))]
[JsonPropertyName("not_before")]
public int NotBefore { get; set; }
public DateTimeOffset NotBefore { get; set; }

[JsonPropertyName("serial_number")]
public string SerialNumber { get; set; }
Expand Down
6 changes: 4 additions & 2 deletions Certstream/Models/MessageData.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
using System;
using System.Text.Json.Serialization;

namespace Certstream.Models
{
Expand All @@ -13,8 +14,9 @@ public struct MessageData
[JsonPropertyName("leaf_cert")]
public LeafCertificate Leaf { get; set; }

[JsonConverter(typeof(UnixDateTimeOffsetConverter))]
[JsonPropertyName("seen")]
public double Seen { get; set; }
public DateTimeOffset Seen { get; set; }

[JsonPropertyName("source")]
public Source Source { get; set; }
Expand Down

0 comments on commit 5aaa783

Please sign in to comment.