Skip to content

Commit

Permalink
Handle scenario when Timestamp is null
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Apr 4, 2022
1 parent 397b6c3 commit b1b1947
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ internal class TimestampConverter : JsonConverter<Timestamp?>

public override Timestamp? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TryGetDateTime(out var dateTime))
if (reader.TokenType == JsonTokenType.String && reader.TryGetDateTime(out var dateTime))
{
return dateTime.ToTimestamp();
}
Expand Down
18 changes: 18 additions & 0 deletions test/Protobuf.System.Text.Json.Tests/MessageWithTimestampTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Text.Json;
using System.Text.Json.Protobuf.Tests;
using System.Text.Json.Serialization;
using Google.Protobuf.WellKnownTypes;
using Protobuf.System.Text.Json.Tests.Utils;
using Shouldly;
Expand Down Expand Up @@ -80,4 +81,21 @@ public void Should_serialize_and_deserialize_message_with_timestamp_when_value_i
deserialized.ShouldNotBeNull();
deserialized.ShouldBeEquivalentTo(msg);
}

[Fact]
public void Should_serialize_and_deserialize_message_with_timestamp_when_value_is_set_to_null()
{
// Arrange
var msg = new MessageWithTimestamp();
var jsonSerializerOptions = TestHelper.CreateJsonSerializerOptions();
jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.Never;

// Act
var serialized = JsonSerializer.Serialize(msg, jsonSerializerOptions);
var deserialized = JsonSerializer.Deserialize<MessageWithTimestamp>(serialized, jsonSerializerOptions);

// Assert
deserialized.ShouldNotBeNull();
deserialized.ShouldBeEquivalentTo(msg);
}
}

0 comments on commit b1b1947

Please sign in to comment.