From 60a0c0221d63a52e74296394432a7fc9cd1f6613 Mon Sep 17 00:00:00 2001 From: Niklas Hamann Date: Thu, 11 Sep 2025 12:45:06 +0200 Subject: [PATCH] Fix nullable porperties serialization exception in `EntryConvert` Issue: Nullable primitive type throws exception on serialization. Solution: Now `EntryConvertGenerator.TransformType()` returns `EntryValueType.Exception` if propertyType parameter is nullable primitive type. [Port for release/6] --- src/Moryx/Serialization/EntryConvert/EntryConvert.cs | 9 +++++++-- src/Tests/Moryx.Tests/Serialization/DummyClass.cs | 5 +++++ .../Moryx.Tests/Serialization/SerializationTests.cs | 8 ++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/Moryx/Serialization/EntryConvert/EntryConvert.cs b/src/Moryx/Serialization/EntryConvert/EntryConvert.cs index 06aaaa7f4..a8a666439 100644 --- a/src/Moryx/Serialization/EntryConvert/EntryConvert.cs +++ b/src/Moryx/Serialization/EntryConvert/EntryConvert.cs @@ -126,8 +126,13 @@ private static EntryValue CreateEntryValue(PropertyInfo property, ICustomSeriali entryValue.Default = defaultAttribute.Value.ToString(); else if (entryValue.Possible != null && entryValue.Possible.Length >= 1) entryValue.Default = entryValue.Possible[0]; - else if (property.PropertyType.IsValueType) - entryValue.Default = Activator.CreateInstance(property.PropertyType).ToString(); + else if (property.PropertyType.IsValueType) + { + var underlyingType = Nullable.GetUnderlyingType(property.PropertyType); + entryValue.Default = underlyingType != null + ? Activator.CreateInstance(underlyingType).ToString() + : Activator.CreateInstance(property.PropertyType).ToString(); + } // Value types should have the default value as current value if (ValueOrStringType(property.PropertyType)) diff --git a/src/Tests/Moryx.Tests/Serialization/DummyClass.cs b/src/Tests/Moryx.Tests/Serialization/DummyClass.cs index fdef23b64..3fa6e43b1 100644 --- a/src/Tests/Moryx.Tests/Serialization/DummyClass.cs +++ b/src/Tests/Moryx.Tests/Serialization/DummyClass.cs @@ -53,4 +53,9 @@ public enum DummyEnum ValueA, ValueB } + + public class NullablePropertiesClass + { + public int? Value { get; set; } = 0; + } } diff --git a/src/Tests/Moryx.Tests/Serialization/SerializationTests.cs b/src/Tests/Moryx.Tests/Serialization/SerializationTests.cs index 52f3e1997..e9efafdb2 100644 --- a/src/Tests/Moryx.Tests/Serialization/SerializationTests.cs +++ b/src/Tests/Moryx.Tests/Serialization/SerializationTests.cs @@ -847,6 +847,14 @@ public void MemoryStreamEncode() Assert.AreEqual("VGhpcyBpcyBhIHRlc3Q=", entry.SubEntries[0].Value.Current); } + [Test(Description = "Testing nullable properties")] + public void NullableProperty() + { + var nullablePropertiesObject = new NullablePropertiesClass(); + + Assert.DoesNotThrow(() => EntryConvert.EncodeObject(nullablePropertiesObject)); + } + [Test(Description = "Decodes to a MemoryStream and creates a new stream")] public void MemoryStreamDecode() {