From 78ff21e144922cdab1084dcf19048e12dcebb60a Mon Sep 17 00:00:00 2001 From: Ethan Shea Date: Sun, 27 Jun 2021 23:44:07 -0700 Subject: [PATCH] Fix nullable struct serialization Addresses #360 --- .../Serialization/SerializationTestHelper.cs | 5 +++++ .../Serialization/SerializationTests.cs | 18 ++++++++++++++++++ .../ObjectNodeDeserializer.cs | 7 +++++-- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/YamlDotNet.Test/Serialization/SerializationTestHelper.cs b/YamlDotNet.Test/Serialization/SerializationTestHelper.cs index 9f43770e3..272245aae 100644 --- a/YamlDotNet.Test/Serialization/SerializationTestHelper.cs +++ b/YamlDotNet.Test/Serialization/SerializationTestHelper.cs @@ -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 } diff --git a/YamlDotNet.Test/Serialization/SerializationTests.cs b/YamlDotNet.Test/Serialization/SerializationTests.cs index e27c66ba3..613a259e4 100644 --- a/YamlDotNet.Test/Serialization/SerializationTests.cs +++ b/YamlDotNet.Test/Serialization/SerializationTests.cs @@ -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(value); + + result.Should().Be(value); + } + + [Fact] + public void RoundtripNullableStructWithoutValue() + { + var result = DoRoundtripFromObjectTo(null); + + result.Should().Be(null); + } + [Fact] public void SerializeCircularReference() { diff --git a/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs b/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs index 4c44b9fb4..559a29f46 100644 --- a/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs +++ b/YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs @@ -47,11 +47,14 @@ bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func(out var _)) { var propertyName = parser.Consume(); - var property = typeDescriptor.GetProperty(expectedType, null, propertyName.Value, ignoreUnmatched); + var property = typeDescriptor.GetProperty(implementationType, null, propertyName.Value, ignoreUnmatched); if (property == null) { parser.SkipThisAndNestedEvents();