public void DynamicSnakeCasePropertyNames() { dynamic o = new TestDynamicObject(); o.Text = "Text!"; o.Integer = int.MaxValue; DefaultContractResolver contractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy { ProcessDictionaryKeys = true } }; string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ContractResolver = contractResolver }); StringAssert.AreEqual(@"{ ""explicit"": false, ""text"": ""Text!"", ""integer"": 2147483647, ""int"": 0, ""child_object"": null }", json); }
public void SerializeDynamicObject() { TestDynamicObject dynamicObject = new TestDynamicObject(); dynamicObject.Explicit = true; dynamic d = dynamicObject; d.Int = 1; d.Decimal = 99.9d; d.ChildObject = new DynamicChildObject(); Dictionary <string, object> values = new Dictionary <string, object>(); IContractResolver c = DefaultContractResolver.Instance; JsonDynamicContract dynamicContract = (JsonDynamicContract)c.ResolveContract(dynamicObject.GetType()); foreach (string memberName in dynamicObject.GetDynamicMemberNames()) { object value; dynamicContract.TryGetMember(dynamicObject, memberName, out value); values.Add(memberName, value); } Assert.AreEqual(d.Int, values["Int"]); Assert.AreEqual(d.Decimal, values["Decimal"]); Assert.AreEqual(d.ChildObject, values["ChildObject"]); string json = JsonConvert.SerializeObject(dynamicObject, Formatting.Indented); StringAssert.AreEqual(@"{ ""Explicit"": true, ""Decimal"": 99.9, ""Int"": 1, ""ChildObject"": { ""Text"": null, ""Integer"": 0 } }", json); TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject <TestDynamicObject>(json); Assert.AreEqual(true, newDynamicObject.Explicit); d = newDynamicObject; Assert.AreEqual(99.9, d.Decimal); Assert.AreEqual(1, d.Int); Assert.AreEqual(dynamicObject.ChildObject.Integer, d.ChildObject.Integer); Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text); }
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, }); StringAssert.AreEqual(@"{ ""Explicit"": false, ""Text"": ""Text!"", ""Int"": 2147483647 }", json); }
public void DynamicCamelCasePropertyNames() { dynamic o = new TestDynamicObject(); o.Text = "Text!"; o.Integer = int.MaxValue; string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); StringAssert.AreEqual(@"{ ""explicit"": false, ""text"": ""Text!"", ""integer"": 2147483647, ""int"": 0, ""childObject"": null }", json); }