From 9335f00628be416c95ef4d93b543966353ea8982 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Sun, 5 May 2013 09:40:10 +0100 Subject: [PATCH] Null is now properly deserialized The deserializer wasn't recognizing null literals as such (~, empty string, null, Null, NULL). As a result, a null string was deserialized as an empty string. Added a test for this (roundtrip + emit defaults). --- .../Serialization/YamlSerializer.cs | 16 +++++----- .../RepresentationModel/SerializationTests.cs | 29 +++++++++++++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/YamlDotNet.RepresentationModel/Serialization/YamlSerializer.cs b/YamlDotNet.RepresentationModel/Serialization/YamlSerializer.cs index 8121ecf..549eef5 100644 --- a/YamlDotNet.RepresentationModel/Serialization/YamlSerializer.cs +++ b/YamlDotNet.RepresentationModel/Serialization/YamlSerializer.cs @@ -335,21 +335,19 @@ namespace YamlDotNet.RepresentationModel.Serialization private bool IsNull(NodeEvent nodeEvent) { + // http://yaml.org/type/null.html + if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } - if (JsonCompatible) - { - var scalar = nodeEvent as Scalar; - if (scalar != null && scalar.Style == Core.ScalarStyle.Plain && scalar.Value == "null") - { - return true; - } - } + var scalar = nodeEvent as Scalar; + if (scalar == null) + return false; - return false; + var value = scalar.Value; + return value == "" || value == "~" || value == "null" || value == "Null" || value == "NULL"; } private object DeserializeValueNotNull(EventReader reader, DeserializationContext context, INodeEvent nodeEvent, Type expectedType) diff --git a/YamlDotNet.UnitTests/RepresentationModel/SerializationTests.cs b/YamlDotNet.UnitTests/RepresentationModel/SerializationTests.cs index 12c4e36..2750952 100644 --- a/YamlDotNet.UnitTests/RepresentationModel/SerializationTests.cs +++ b/YamlDotNet.UnitTests/RepresentationModel/SerializationTests.cs @@ -197,6 +197,35 @@ namespace YamlDotNet.UnitTests.RepresentationModel } } + [Fact] + public void RoundtripWithDefaults() + { + var serializer = new Serializer(); + + using (StringWriter buffer = new StringWriter()) + { + X original = new X(); + serializer.Serialize(buffer, original, SerializationOptions.Roundtrip | SerializationOptions.EmitDefaults); + + Console.WriteLine(buffer.ToString()); + + var deserializer = new YamlSerializer(typeof(X), YamlSerializerModes.Roundtrip); + X copy = (X)deserializer.Deserialize(new StringReader(buffer.ToString())); + + foreach (var property in typeof(X).GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.CanRead && property.CanWrite) + { + Assert.Equal( + property.GetValue(original, null), + property.GetValue(copy, null) + ); + } + } + } + } + + private class Y { private Y child;