public void ObjectEventsDocumentationExample() { SerializationEventTestObject obj = new SerializationEventTestObject(); Assert.AreEqual(11, obj.Member1); Assert.AreEqual("Hello World!", obj.Member2); Assert.AreEqual("This is a nonserialized value", obj.Member3); Assert.AreEqual(null, obj.Member4); Assert.AreEqual(null, obj.Member5); string json = JsonConvertX.SerializeObject(obj, Formatting.Indented); StringAssert.AreEqual(@"{ ""Member1"": 11, ""Member2"": ""This value went into the data file during serialization."", ""Member4"": null }", json); Assert.AreEqual(11, obj.Member1); Assert.AreEqual("This value was reset after serialization.", obj.Member2); Assert.AreEqual("This is a nonserialized value", obj.Member3); Assert.AreEqual(null, obj.Member4); Assert.AreEqual("Error message for member Member6 = Error getting value from 'Member6' on 'Newtonsoft.Json.Tests.TestObjects.SerializationEventTestObject'.", obj.Member5); obj = JsonConvertX.DeserializeObject <SerializationEventTestObject>(json); Assert.AreEqual(11, obj.Member1); Assert.AreEqual("This value went into the data file during serialization.", obj.Member2); Assert.AreEqual("This value was set during deserialization", obj.Member3); Assert.AreEqual("This value was set after deserialization.", obj.Member4); Assert.AreEqual(null, obj.Member5); }
public void Include() { Invoice invoice = new Invoice { Company = "Acme Ltd.", Amount = 50.0m, Paid = false, FollowUpDays = 30, FollowUpEmailAddress = string.Empty, PaidDate = null }; string included = JsonConvertX.SerializeObject(invoice, Formatting.Indented, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Include }); StringAssert.AreEqual(@"{ ""Company"": ""Acme Ltd."", ""Amount"": 50.0, ""Paid"": false, ""PaidDate"": null, ""FollowUpDays"": 30, ""FollowUpEmailAddress"": """" }", included); }
public void DefaultValueHandlingPropertyTest() { DefaultValueHandlingPropertyClass c = new DefaultValueHandlingPropertyClass(); string json = JsonConvertX.SerializeObject(c, Formatting.Indented); StringAssert.AreEqual(@"{ ""IntInclude"": 0, ""IntDefault"": 0 }", json); json = JsonConvertX.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); StringAssert.AreEqual(@"{ ""IntInclude"": 0 }", json); json = JsonConvertX.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Include }); StringAssert.AreEqual(@"{ ""IntInclude"": 0, ""IntDefault"": 0 }", json); }
public void SerializeEmployeeReference() { EmployeeReference mikeManager = new EmployeeReference { Name = "Mike Manager" }; EmployeeReference joeUser = new EmployeeReference { Name = "Joe User", Manager = mikeManager }; List <EmployeeReference> employees = new List <EmployeeReference> { mikeManager, joeUser }; string json = JsonConvertX.SerializeObject(employees, Formatting.Indented); StringAssert.AreEqual(@"[ { ""$id"": ""1"", ""Name"": ""Mike Manager"", ""Manager"": null }, { ""$id"": ""2"", ""Name"": ""Joe User"", ""Manager"": { ""$ref"": ""1"" } } ]", json); }
public void DeserializeReferenceInList() { string json = @"[ { ""$id"": ""1"", ""Name"": ""e1"", ""Manager"": null }, { ""$id"": ""2"", ""Name"": ""e2"", ""Manager"": null }, { ""$ref"": ""1"" }, { ""$ref"": ""2"" } ]"; List <EmployeeReference> employees = JsonConvertX.DeserializeObject <List <EmployeeReference> >(json); Assert.AreEqual(4, employees.Count); Assert.AreEqual("e1", employees[0].Name); Assert.AreEqual("e2", employees[1].Name); Assert.AreEqual("e1", employees[2].Name); Assert.AreEqual("e2", employees[3].Name); Assert.AreEqual(employees[0], employees[2]); Assert.AreEqual(employees[1], employees[3]); }
public void IgnoreObjectReferenceLoopWithPropertyOverride() { ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride o = new ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride(); o.Value = o; string json = JsonConvertX.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize }); StringAssert.AreEqual(@"{ ""Value"": { ""Value"": { ""Value"": { ""Value"": { ""Value"": { ""Value"": null } } } } } }", json); }
public void SerializeDictionarysWithPreserveObjectReferences() { CircularDictionary circularDictionary = new CircularDictionary(); circularDictionary.Add("other", new CircularDictionary { { "blah", null } }); circularDictionary.Add("self", circularDictionary); string json = JsonConvertX.SerializeObject(circularDictionary, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); StringAssert.AreEqual(@"{ ""$id"": ""1"", ""other"": { ""$id"": ""2"", ""blah"": null }, ""self"": { ""$ref"": ""1"" } }", json); }
public void DataBagDoesNotInheritFromDictionaryClass() { Example e = new Example(); e.Data.Add("extensionData1", new int[] { 1, 2, 3 }); string json = JsonConvertX.SerializeObject(e, Formatting.Indented); StringAssert.AreEqual(@"{ ""extensionData1"": [ 1, 2, 3 ] }", json); Example e2 = JsonConvertX.DeserializeObject <Example>(json); JArray o1 = (JArray)e2.Data["extensionData1"]; Assert.AreEqual(JTokenType.Array, o1.Type); Assert.AreEqual(3, o1.Count); Assert.AreEqual(1, (int)o1[0]); Assert.AreEqual(2, (int)o1[1]); Assert.AreEqual(3, (int)o1[2]); }
public void ExtensionDataTest() { string json = @"{ ""Ints"": [1,2,3], ""Ignored"": [1,2,3], ""Readonly"": ""Readonly"", ""Name"": ""Actually set!"", ""CustomName"": ""Wrong name!"", ""GetPrivate"": true, ""GetOnly"": true, ""NewValueSimple"": true, ""NewValueComplex"": [1,2,3] }"; ExtensionDataTestClass c = JsonConvertX.DeserializeObject <ExtensionDataTestClass>(json); Assert.AreEqual("Actually set!", c.Name); Assert.AreEqual(4, c.Ints.Count); Assert.AreEqual("Readonly", (string)c.ExtensionData["Readonly"]); Assert.AreEqual("Wrong name!", (string)c.ExtensionData["CustomName"]); Assert.AreEqual(true, (bool)c.ExtensionData["GetPrivate"]); Assert.AreEqual(true, (bool)c.ExtensionData["GetOnly"]); Assert.AreEqual(true, (bool)c.ExtensionData["NewValueSimple"]); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["NewValueComplex"])); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["Ignored"])); Assert.AreEqual(7, c.ExtensionData.Count); }
public void DeserializingErrorInChildObject() { ListErrorObjectCollection c = JsonConvertX.DeserializeObject <ListErrorObjectCollection>(@"[ { ""Member"": ""Value1"", ""Member2"": null }, { ""Member"": ""Value2"" }, { ""ThrowError"": ""Value"", ""Object"": { ""Array"": [ 1, 2 ] } }, { ""ThrowError"": ""Handle this!"", ""Member"": ""Value3"" } ]"); Assert.AreEqual(3, c.Count); Assert.AreEqual("Value1", c[0].Member); Assert.AreEqual("Value2", c[1].Member); Assert.AreEqual("Value3", c[2].Member); Assert.AreEqual("Handle this!", c[2].ThrowError); }
public void SerializeSerializableType() { SerializableType serializableType = new SerializableType("protected") { publicField = "public", protectedInternalField = "protected internal", internalField = "internal", PublicProperty = "private", nonSerializedField = "Error" }; #if !(NET20 || NET35 || PORTABLE || DNXCORE50 || PORTABLE40) MemoryStream ms = new MemoryStream(); DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(SerializableType)); dataContractJsonSerializer.WriteObject(ms, serializableType); string dtJson = Encoding.UTF8.GetString(ms.ToArray()); string dtExpected = @"{""internalField"":""internal"",""privateField"":""private"",""protectedField"":""protected"",""protectedInternalField"":""protected internal"",""publicField"":""public""}"; Assert.AreEqual(dtExpected, dtJson); #endif string expected = "{\"publicField\":\"public\",\"internalField\":\"internal\",\"protectedInternalField\":\"protected internal\",\"protectedField\":\"protected\",\"privateField\":\"private\"}"; string json = JsonConvertX.SerializeObject(serializableType, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { #if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 IgnoreSerializableAttribute = false #endif } }); Assert.AreEqual(expected, json); }
public void ErrorDeserializingListHandled() { string json = @"[ { ""Name"": ""Jim"", ""BirthDate"": ""\/Date(978048000000)\/"", ""LastModified"": ""\/Date(978048000000)\/"" }, { ""Name"": ""Jim"", ""BirthDate"": ""\/Date(978048000000)\/"", ""LastModified"": ""\/Date(978048000000)\/"" } ]"; var possibleMsgs = new[] { "[1] - Error message for member 1 = An item with the same key has already been added.", "[1] - Error message for member 1 = An element with the same key already exists in the dictionary.", // mono "[1] - Error message for member 1 = An item with the same key has already been added. Key: Jim" // netcore }; VersionKeyedCollection c = JsonConvertX.DeserializeObject <VersionKeyedCollection>(json); Assert.AreEqual(1, c.Count); Assert.AreEqual(1, c.Messages.Count); Console.WriteLine(c.Messages[0]); Assert.IsTrue(possibleMsgs.Any(m => m == c.Messages[0]), "Expected One of: " + Environment.NewLine + string.Join(Environment.NewLine, possibleMsgs) + Environment.NewLine + "Was: " + Environment.NewLine + c.Messages[0]); }
public void DictionaryCamelCasePropertyNames_Enabled() { Dictionary <string, string> values = new Dictionary <string, string> { { "First", "Value1!" }, { "Second", "Value2!" } }; DefaultContractResolver contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { ProcessDictionaryKeys = true } }; string json = JsonConvertX.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings { ContractResolver = contractResolver }); StringAssert.AreEqual(@"{ ""first"": ""Value1!"", ""second"": ""Value2!"" }", json); }
public void DynamicCamelCasePropertyNames() { dynamic o = new TestDynamicObject(); o.Text = "Text!"; o.Integer = int.MaxValue; DefaultContractResolver contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { ProcessDictionaryKeys = true } }; string json = JsonConvertX.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ContractResolver = contractResolver }); StringAssert.AreEqual(@"{ ""explicit"": false, ""text"": ""Text!"", ""integer"": 2147483647, ""int"": 0, ""childObject"": null }", json); }
public void SerializePropertyItemReferenceLoopHandling() { PropertyItemReferenceLoopHandling c = new PropertyItemReferenceLoopHandling(); c.Text = "Text!"; c.SetData(new List <PropertyItemReferenceLoopHandling> { c }); string json = JsonConvertX.SerializeObject(c, Formatting.Indented); StringAssert.AreEqual(@"{ ""Text"": ""Text!"", ""Data"": [ { ""Text"": ""Text!"", ""Data"": [ { ""Text"": ""Text!"", ""Data"": [ { ""Text"": ""Text!"", ""Data"": null } ] } ] } ] }", json); }
public void ExtensionDataTest_SerializeWithNamingStrategyAttribute() { ExtensionDataWithNamingStrategyTestClass c = new ExtensionDataWithNamingStrategyTestClass() { ExtensionData = new Dictionary <string, JToken> { ["TestValue1"] = 1, ["alreadyCamelCase"] = new JObject { ["NotProcessed"] = true } } }; string json = JsonConvertX.SerializeObject(c, new JsonSerializerSettings { Formatting = Formatting.Indented }); StringAssert.AreEqual(@"{ ""name"": null, ""testValue1"": 1, ""alreadyCamelCase"": { ""NotProcessed"": true } }", json); }
public void EqualityComparer() { AccountWithEquals account = new AccountWithEquals { Name = "main" }; AccountWithEquals manager = new AccountWithEquals { Name = "main" }; account.Manager = manager; ExceptionAssert.Throws <JsonSerializationException>( () => JsonConvertX.SerializeObject(account), "Self referencing loop detected for property 'Manager' with type 'JsonExtensions.Tests.Serialization.AccountWithEquals'. Path ''."); string json = JsonConvertX.SerializeObject(account, new JsonSerializerSettings { EqualityComparer = new ReferenceEqualsEqualityComparer(), Formatting = Formatting.Indented }); StringAssert.AreEqual(@"{ ""Name"": ""main"", ""Manager"": { ""Name"": ""main"", ""Manager"": null } }", json); }
public void DeserializePublicExtensionDataTypeNamdHandlingNonDefaultConstructor() { string json = @"{ ""$id"": ""1"", ""Name"": ""Name!"", ""Test"": 1, ""Self"": { ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Organization.WagePerson, JsonExtensions.Tests"", ""HourlyWage"": 2.0, ""Name"": null, ""BirthDate"": ""0001-01-01T00:00:00"", ""LastModified"": ""0001-01-01T00:00:00"" } }"; PublicExtensionDataAttributeTestClassWithNonDefaultConstructor c2 = JsonConvertX.DeserializeObject <PublicExtensionDataAttributeTestClassWithNonDefaultConstructor>(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }); Assert.AreEqual("Name!", c2.Name); WagePerson bizzaroC2 = (WagePerson)c2.ExtensionData["Self"]; Assert.AreEqual(2m, bizzaroC2.HourlyWage); }
public void ExampleWithout() { Person p = new Person { BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc), LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc), Department = "IT", Name = "James" }; List <Person> people = new List <Person>(); people.Add(p); people.Add(p); string json = JsonConvertX.SerializeObject(people, Formatting.Indented); //[ // { // "Name": "James", // "BirthDate": "\/Date(346377600000)\/", // "LastModified": "\/Date(1235134761000)\/" // }, // { // "Name": "James", // "BirthDate": "\/Date(346377600000)\/", // "LastModified": "\/Date(1235134761000)\/" // } //] }
public void SerializePublicExtensionDataTypeNamdHandling() { PublicExtensionDataAttributeTestClass c = new PublicExtensionDataAttributeTestClass { Name = "Name!", ExtensionData = new Dictionary <object, object> { { "Test", new WagePerson { HourlyWage = 2.1m } } } }; string json = JsonConvertX.SerializeObject(c, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, Formatting = Formatting.Indented }); StringAssert.AreEqual(@"{ ""$type"": ""JsonExtensions.Tests.Serialization.ExtensionDataTests+PublicExtensionDataAttributeTestClass, JsonExtensions.Tests"", ""Name"": ""Name!"", ""Test"": { ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Organization.WagePerson, JsonExtensions.Tests"", ""HourlyWage"": 2.1, ""Name"": null, ""BirthDate"": ""0001-01-01T00:00:00"", ""LastModified"": ""0001-01-01T00:00:00"" } }", json); }
public void SerializeCircularListsIgnore() { CircularList circularList = new CircularList(); circularList.Add(null); circularList.Add(new CircularList { null }); circularList.Add(new CircularList { new CircularList { circularList } }); string json = JsonConvertX.SerializeObject(circularList, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); StringAssert.AreEqual(@"[ null, [ null ], [ [] ] ]", json); }
public void MemberSearchFlags() { PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!"); string json = JsonConvertX.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance } }); StringAssert.AreEqual(@"{ ""_privateString"": ""PrivateString!"", ""i"": 0, ""_internalString"": ""InternalString!"" }", json); PrivateMembersClass deserializedPrivateMembersClass = JsonConvertX.DeserializeObject <PrivateMembersClass>(@"{ ""_privateString"": ""Private!"", ""i"": -2, ""_internalString"": ""Internal!"" }", new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance } }); Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass)); Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass)); // readonly Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass)); }
public void DeserializeCircularReference() { string json = @"{ ""$id"": ""1"", ""Name"": ""c1"", ""Child"": { ""$id"": ""2"", ""Name"": ""c2"", ""Child"": { ""$id"": ""3"", ""Name"": ""c3"", ""Child"": { ""$ref"": ""1"" } } } }"; CircularReferenceClass c1 = JsonConvertX.DeserializeObject <CircularReferenceClass>(json, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }); Assert.AreEqual("c1", c1.Name); Assert.AreEqual("c2", c1.Child.Name); Assert.AreEqual("c3", c1.Child.Child.Name); Assert.AreEqual("c1", c1.Child.Child.Child.Name); }
public void JsonConvertSerializerSettings() { Person person = new Person(); person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc); person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc); person.Name = "Name!"; string json = JsonConvertX.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); StringAssert.AreEqual(@"{ ""name"": ""Name!"", ""birthDate"": ""2000-11-20T23:55:44Z"", ""lastModified"": ""2000-11-20T23:55:44Z"" }", json); Person deserializedPerson = JsonConvertX.DeserializeObject <Person>(json, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate); Assert.AreEqual(person.LastModified, deserializedPerson.LastModified); Assert.AreEqual(person.Name, deserializedPerson.Name); json = JsonConvertX.SerializeObject(person, Formatting.Indented); StringAssert.AreEqual(@"{ ""Name"": ""Name!"", ""BirthDate"": ""2000-11-20T23:55:44Z"", ""LastModified"": ""2000-11-20T23:55:44Z"" }", json); }
public void DeserializeReferenceInDictionary() { string json = @"{ ""One"": { ""$id"": ""1"", ""Name"": ""e1"", ""Manager"": null }, ""Two"": { ""$id"": ""2"", ""Name"": ""e2"", ""Manager"": null }, ""Three"": { ""$ref"": ""1"" }, ""Four"": { ""$ref"": ""2"" } }"; Dictionary <string, EmployeeReference> employees = JsonConvertX.DeserializeObject <Dictionary <string, EmployeeReference> >(json); Assert.AreEqual(4, employees.Count); EmployeeReference e1 = employees["One"]; EmployeeReference e2 = employees["Two"]; Assert.AreEqual("e1", e1.Name); Assert.AreEqual("e2", e2.Name); Assert.AreEqual(e1, employees["Three"]); Assert.AreEqual(e2, employees["Four"]); }
public void ConstructorParametersRespectDefaultValueTest() { var testObject = JsonConvertX.DeserializeObject<ConstructorParametersRespectDefaultValue>("{}", new JsonSerializerSettings() { ContractResolver = ConstructorParameterDefaultStringValueContractResolver.Instance }); Assert.AreEqual("Default Value", testObject.Parameter1); Assert.AreEqual("Default Value", testObject.Parameter2); }
public void SerializeDefaultValueAttributeTest() { string json = JsonConvertX.SerializeObject(new DefaultValueAttributeTestClass(), Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); Assert.AreEqual(@"{""TestField1"":0,""TestProperty1"":null}", json); json = JsonConvertX.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = int.MinValue, TestProperty1 = "NotDefault" }, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); Assert.AreEqual(@"{""TestField1"":-2147483648,""TestProperty1"":""NotDefault""}", json); json = JsonConvertX.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "NotDefault" }, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); Assert.AreEqual(@"{""TestProperty1"":""NotDefault""}", json); json = JsonConvertX.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "TestProperty1Value" }, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); Assert.AreEqual(@"{}", json); }
public void Run() { var dict = new Dictionary <string, object> { { "KeyA", 101 }, { "KeyB", Guid.NewGuid() }, { "KeyC", CombGuid.NewComb() }, }; var json = JsonConvertX.SerializeObject(dict); var newDict = JsonConvertX.DeserializeObject <Dictionary <string, object> >(json); Assert.AreEqual((int)dict["KeyA"], newDict.Deserialize <int>("KeyA")); Assert.AreEqual((Guid)dict["KeyB"], newDict.Deserialize <Guid>("KeyB")); Assert.AreEqual((CombGuid)dict["KeyC"], newDict.Deserialize <CombGuid>("KeyC")); #if !NET40 json = SpanJson.JsonSerializer.Generic.Utf16.Serialize(dict); newDict = SpanJson.JsonSerializer.Generic.Utf16.Deserialize <Dictionary <string, object> >(json); Assert.AreEqual((int)dict["KeyA"], newDict.Deserialize <int>("KeyA")); Assert.AreEqual((Guid)dict["KeyB"], newDict.Deserialize <Guid>("KeyB")); Assert.AreEqual((CombGuid)dict["KeyC"], newDict.Deserialize <CombGuid>("KeyC")); #endif }
public void CreateObjectWithParameters() { int count = 0; ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType <TaskRepository>().As <ITaskRepository>(); builder.RegisterType <TaskController>(); builder.Register(c => { count++; return(new LogManager(new DateTime(2000, 12, 12))); }).As <ILogger>(); IContainer container = builder.Build(); AutofacContractResolver contractResolver = new AutofacContractResolver(container); TaskController controller = JsonConvertX.DeserializeObject <TaskController>(@"{ 'Logger': { 'Level':'Debug' } }", new JsonSerializerSettings { ContractResolver = contractResolver }); Assert.IsNotNull(controller); Assert.IsNotNull(controller.Logger); Assert.AreEqual(1, count); Assert.AreEqual(new DateTime(2000, 12, 12), controller.Logger.DateTime); Assert.AreEqual("Debug", controller.Logger.Level); }
public void ObjectWithConstructorEvents() { SerializationEventTestObjectWithConstructor obj = new SerializationEventTestObjectWithConstructor(11, "Hello World!", null); Assert.AreEqual(11, obj.Member1); Assert.AreEqual("Hello World!", obj.Member2); Assert.AreEqual("This is a nonserialized value", obj.Member3); Assert.AreEqual(null, obj.Member4); string json = JsonConvertX.SerializeObject(obj, Formatting.Indented); StringAssert.AreEqual(@"{ ""Member1"": 11, ""Member2"": ""This value went into the data file during serialization."", ""Member4"": null }", json); Assert.AreEqual(11, obj.Member1); Assert.AreEqual("This value was reset after serialization.", obj.Member2); Assert.AreEqual("This is a nonserialized value", obj.Member3); Assert.AreEqual(null, obj.Member4); obj = JsonConvertX.DeserializeObject <SerializationEventTestObjectWithConstructor>(json); Assert.AreEqual(11, obj.Member1); Assert.AreEqual("This value went into the data file during serialization.", obj.Member2); Assert.AreEqual("This value was set during deserialization", obj.Member3); Assert.AreEqual("This value was set after deserialization.", obj.Member4); }