2 using System.Collections.Generic;
3 using System.ComponentModel;
6 using Newtonsoft.Json.Tests.TestObjects;
9 namespace Newtonsoft.Json.Tests.Serialization
11 public class DefaultValueHandlingTests : TestFixtureBase
14 public void SerializeInvoice()
16 Invoice invoice = new Invoice
18 Company = "Acme Ltd.",
22 FollowUpEmailAddress = string.Empty,
26 string included = JsonConvert.SerializeObject(invoice,
28 new JsonSerializerSettings { });
31 // "Company": "Acme Ltd.",
35 // "FollowUpDays": 30,
36 // "FollowUpEmailAddress": ""
39 string ignored = JsonConvert.SerializeObject(invoice,
41 new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
44 // "Company": "Acme Ltd.",
48 Console.WriteLine(included);
49 Console.WriteLine(ignored);
53 public void DefaultValueAttributeTest()
55 string json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass(),
56 Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
57 Assert.AreEqual(@"{""TestField1"":0,""TestProperty1"":null}", json);
59 json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = int.MinValue, TestProperty1 = "NotDefault" },
60 Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
61 Assert.AreEqual(@"{""TestField1"":-2147483648,""TestProperty1"":""NotDefault""}", json);
63 json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "NotDefault" },
64 Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
65 Assert.AreEqual(@"{""TestProperty1"":""NotDefault""}", json);
67 json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "TestProperty1Value" },
68 Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
69 Assert.AreEqual(@"{}", json);
73 public class NetworkUser
75 [JsonProperty(PropertyName = "userId")]
77 public long GlobalId { get; set; }
79 [JsonProperty(PropertyName = "floatUserId")]
81 public float FloatGlobalId { get; set; }
83 [JsonProperty(PropertyName = "firstName")]
84 public string Firstname { get; set; }
85 [JsonProperty(PropertyName = "lastName")]
86 public string Lastname { get; set; }
91 FloatGlobalId = -1.0f;
96 public void IgnoreNumberTypeDifferencesWithDefaultValue()
98 NetworkUser user = new NetworkUser
103 string json = JsonConvert.SerializeObject(user, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
105 Assert.AreEqual(@"{""firstName"":""blub""}", json);