-Added NullValueHandling and DefaultValueHandling support to serializing dynamic properties

This commit is contained in:
James Newton-King
2013-05-01 20:26:05 +12:00
parent 2b9941fa74
commit da491c3a0f
2 changed files with 87 additions and 0 deletions
@@ -250,6 +250,78 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(false, foo.Values["retweeted"]);
}
[Test]
public void SerializeDynamicObjectWithNullValueHandlingIgnore()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Int = int.MaxValue;
o.ChildObject = null; // Tests an explicitly defined property of a dynamic object with a null value.
o.DynamicChildObject = null; // vs. a completely dynamic defined property.
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
});
Console.WriteLine(json);
Assert.AreEqual(@"{
""Explicit"": false,
""Text"": ""Text!"",
""Int"": 2147483647
}", json);
}
[Test]
public void SerializeDynamicObjectWithNullValueHandlingInclude()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Int = int.MaxValue;
o.ChildObject = null; // Tests an explicitly defined property of a dynamic object with a null value.
o.DynamicChildObject = null; // vs. a completely dynamic defined property.
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include,
});
Console.WriteLine(json);
Assert.AreEqual(@"{
""Explicit"": false,
""Text"": ""Text!"",
""DynamicChildObject"": null,
""Int"": 2147483647,
""ChildObject"": null
}", json);
}
[Test]
public void SerializeDynamicObjectWithDefaultValueHandlingIgnore()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Int = int.MaxValue;
o.IntDefault = 0;
o.NUllableIntDefault = default(int?);
o.ChildObject = null; // Tests an explicitly defined property of a dynamic object with a null value.
o.DynamicChildObject = null; // vs. a completely dynamic defined property.
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
});
Console.WriteLine(json);
Assert.AreEqual(@"{
""Text"": ""Text!"",
""Int"": 2147483647
}", json);
}
}
public class DynamicChildObject