Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix nullable struct serialization #621

Merged
merged 1 commit into from
Jun 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ public enum EnumExample
Two
}

public struct StructExample
{
public int Value { get; set; }
}

public enum SByteEnum : sbyte { Default, Sbyte }
public enum ByteEnum : byte { Default, Byte }
public enum Int16Enum : short { Default, Short }
Expand Down
18 changes: 18 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,24 @@ public void RoundtripNullableEnums(EnumExample? value)
result.Should().Be(value);
}

[Fact]
public void RoundtripNullableStructWithValue()
{
var value = new StructExample { Value = 2 };

var result = DoRoundtripFromObjectTo<StructExample?>(value);

result.Should().Be(value);
}

[Fact]
public void RoundtripNullableStructWithoutValue()
{
var result = DoRoundtripFromObjectTo<StructExample?>(null);

result.Should().Be(null);
}

[Fact]
public void SerializeCircularReference()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,14 @@ bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IPars
return false;
}

value = objectFactory.Create(expectedType);
// Strip off the nullable type, if present. This is needed for nullable structs.
var implementationType = Nullable.GetUnderlyingType(expectedType) ?? expectedType;

value = objectFactory.Create(implementationType);
while (!parser.TryConsume<MappingEnd>(out var _))
{
var propertyName = parser.Consume<Scalar>();
var property = typeDescriptor.GetProperty(expectedType, null, propertyName.Value, ignoreUnmatched);
var property = typeDescriptor.GetProperty(implementationType, null, propertyName.Value, ignoreUnmatched);
if (property == null)
{
parser.SkipThisAndNestedEvents();
Expand Down