Skip to content

Commit

Permalink
Handle null values properly during deserialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Mar 28, 2022
1 parent 0876f3e commit c4194f4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Protobuf.System.Text.Json/ProtobufConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,19 @@ private static Func<FieldDescriptor, string> GetConvertNameFunc(JsonNamingPolicy
return descriptor => descriptor.PropertyName;
}

public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var obj = new T();

if (reader.TokenType == JsonTokenType.Null)
{
return null;
}

if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException($"The JSON value could not be converted to {typeToConvert}.");
}

var obj = new T();

// Process all properties.
while (true)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Text.Json;
using System.Text.Json.Protobuf.Tests;
using System.Text.Json.Serialization;
using Protobuf.System.Text.Json.Tests.Utils;
using Shouldly;
using SmartAnalyzers.ApprovalTestsExtensions;
Expand Down Expand Up @@ -45,6 +46,29 @@ public void Should_deserialize_message_with_complex_property()

var jsonSerializerOptions = TestHelper.CreateJsonSerializerOptions();

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

// Assert
deserialized.ShouldBeEquivalentTo(msg);
}

[Fact]
public void Should_deserialize_message_with_complex_property_when_no_value_is_set()
{
// Arrange
var msg = new MessageWithComplexProperty
{
NestedMessage = null
};

var jsonSerializerOptions = TestHelper.CreateJsonSerializerOptions();

// make sure the value won't be ignored
jsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.Never;


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

0 comments on commit c4194f4

Please sign in to comment.