Exemplo n.º 1
0
        public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid()
        {
            const string contextKey = "k1";
            var          someValue  = new Guid("5dd2dba0-20c0-49f8-a054-1fa3b0a8d774");

            Dictionary <string, Guid> inputContext = new Dictionary <string, Guid>();

            inputContext.Add(contextKey, someValue);

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting               = Formatting.Indented,
                TypeNameHandling         = TypeNameHandling.All,
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
            };
            string serializedString = JsonConvertX.SerializeObject(inputContext, jsonSerializerSettings);

            StringAssert.AreEqual(@"{
  ""$type"": """ + ReflectionUtils.GetTypeName(typeof(Dictionary <string, Guid>), 0, PreserveReferencesHandlingTests._bingderInstance) + @""",
  ""k1"": ""5dd2dba0-20c0-49f8-a054-1fa3b0a8d774""
}", serializedString);

            var deserializedObject = (Dictionary <string, Guid>)JsonConvertX.DeserializeObject(serializedString, jsonSerializerSettings);

            Assert.AreEqual(someValue, deserializedObject[contextKey]);
        }
        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 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 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 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
        }
Exemplo n.º 6
0
        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]);
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
0
        public void PrimitiveType_MetadataPropertyIgnore_WithNoType()
        {
            ItemWithUntypedPayload actual = JsonConvertX.DeserializeObject <ItemWithUntypedPayload>(@"{
  ""Payload"": {
    ""$type"": ""System.Single, mscorlib"",
    ""$value"": ""5""
  }
}",
                                                                                                    new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto
            });

            Assert.AreEqual(5f, actual.Payload);

            actual = JsonConvertX.DeserializeObject <ItemWithUntypedPayload>(@"{
  ""Payload"": {
    ""$type"": ""System.Single, mscorlib"",
    ""$value"": ""5""
  }
}",
                                                                             new JsonSerializerSettings
            {
                TypeNameHandling         = TypeNameHandling.Auto,
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore
            });

            Assert.IsTrue(actual.Payload is JObject);
        }
Exemplo n.º 9
0
        public void DeserializeObject()
        {
            string json = @"
  {
    ""Value"": ""2017-12-05T21:59:00""
  }";

            DateTimeWrapper c1 = JsonConvertX.DeserializeObject <DateTimeWrapper>(json, new JsonSerializerSettings()
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            });

            DateTimeWrapper c2 = JsonConvertX.DeserializeObject <DateTimeWrapper>(json, new JsonSerializerSettings()
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            });

            DateTimeWrapper c3 = JsonConvertX.DeserializeObject <DateTimeWrapper>(json, new JsonSerializerSettings()
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
            });

            DateTimeWrapper c4 = JsonConvertX.DeserializeObject <DateTimeWrapper>(json);

            Assert.AreEqual(DateTimeKind.Utc, c1.Value.Kind);
            Assert.AreEqual(DateTimeKind.Local, c2.Value.Kind);
            Assert.AreEqual(DateTimeKind.Unspecified, c3.Value.Kind);
            Assert.AreEqual(DateTimeKind.Unspecified, c4.Value.Kind);
        }
Exemplo n.º 10
0
        public void PrimitiveType_MetadataPropertyIgnore()
        {
            Item actual = JsonConvertX.DeserializeObject <Item>(@"{
  ""SourceTypeID"": ""d8220a4b-75b1-4b7a-8112-b7bdae956a45"",
  ""BrokerID"": ""951663c4-924e-4c86-a57a-7ed737501dbd"",
  ""Latitude"": 33.657145,
  ""Longitude"": -117.766684,
  ""TimeStamp"": ""2000-03-01T23:59:59Z"",
  ""Payload"": {
    ""$type"": ""System.Byte[], mscorlib"",
    ""$value"": ""AAECAwQFBgcICQ==""
  }
}",
                                                                new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore
            });

            Assert.AreEqual(new Guid("d8220a4b-75b1-4b7a-8112-b7bdae956a45"), actual.SourceTypeID);
            Assert.AreEqual(new Guid("951663c4-924e-4c86-a57a-7ed737501dbd"), actual.BrokerID);
            JObject o = (JObject)actual.Payload;

            Assert.AreEqual("System.Byte[], mscorlib", (string)o["$type"]);
            Assert.AreEqual("AAECAwQFBgcICQ==", (string)o["$value"]);
            Assert.AreEqual(null, o.Parent);
        }
Exemplo n.º 11
0
        public void ReadAhead_TypedJValue_NoParent()
        {
            ItemWithJTokens actual = (ItemWithJTokens)JsonConvertX.DeserializeObject(@"{
  ""Payload1"": 1,
  ""Payload2"": {'prop1':1,'prop2':[2]},
  ""Payload3"": [1],
  ""$type"": ""JsonExtensions.Tests.Serialization.MetadataPropertyHandlingTests+ItemWithJTokens, JsonExtensions.Tests""
}",
                                                                                     new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
                TypeNameHandling         = TypeNameHandling.All
            });

            Assert.AreEqual(JTokenType.Integer, actual.Payload1.Type);
            Assert.AreEqual(1, (int)actual.Payload1);
            Assert.AreEqual(null, actual.Payload1.Parent);

            Assert.AreEqual(JTokenType.Object, actual.Payload2.Type);
            Assert.AreEqual(1, (int)actual.Payload2["prop1"]);
            Assert.AreEqual(2, (int)actual.Payload2["prop2"][0]);
            Assert.AreEqual(null, actual.Payload2.Parent);

            Assert.AreEqual(1, (int)actual.Payload3[0]);
            Assert.AreEqual(null, actual.Payload3.Parent);
        }
Exemplo n.º 12
0
        public void MetadataPropertyHandlingIgnore()
        {
            MetadataPropertyDisabledTestClass c1 = new MetadataPropertyDisabledTestClass
            {
                Id     = "Id!",
                Ref    = "Ref!",
                Type   = "Type!",
                Value  = "Value!",
                Values = "Values!"
            };

            string json = JsonConvertX.SerializeObject(c1, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""$id"": ""Id!"",
  ""$ref"": ""Ref!"",
  ""$value"": ""Value!"",
  ""$values"": ""Values!"",
  ""$type"": ""Type!""
}", json);

            MetadataPropertyDisabledTestClass c2 = JsonConvertX.DeserializeObject <MetadataPropertyDisabledTestClass>(json, new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore
            });

            Assert.AreEqual("Id!", c2.Id);
            Assert.AreEqual("Ref!", c2.Ref);
            Assert.AreEqual("Type!", c2.Type);
            Assert.AreEqual("Value!", c2.Value);
            Assert.AreEqual("Values!", c2.Values);
        }
Exemplo n.º 13
0
        public void DeserializeEmployeeReference()
        {
            string json = @"[
  {
    ""Name"": ""Mike Manager"",
    ""$id"": ""1"",
    ""Manager"": null
  },
  {
    ""Name"": ""Joe User"",
    ""$id"": ""2"",
    ""Manager"": {
      ""$ref"": ""1""
    }
  }
]";

            List <EmployeeReference> employees = JsonConvertX.DeserializeObject <List <EmployeeReference> >(json, new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
            });

            Assert.AreEqual(2, employees.Count);
            Assert.AreEqual("Mike Manager", employees[0].Name);
            Assert.AreEqual("Joe User", employees[1].Name);
            Assert.AreEqual(employees[0], employees[1].Manager);
        }
Exemplo n.º 14
0
        public void SerializeRefNull()
        {
            var reference = new Dictionary <string, object>();

            reference.Add("blah", "blah!");
            reference.Add("$ref", null);
            reference.Add("$id", null);

            var child = new Dictionary <string, object>();

            child.Add("_id", 2);
            child.Add("Name", "Isabell");
            child.Add("Father", reference);

            string json = JsonConvertX.SerializeObject(child, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""_id"": 2,
  ""Name"": ""Isabell"",
  ""Father"": {
    ""blah"": ""blah!"",
    ""$ref"": null,
    ""$id"": null
  }
}", json);

            Dictionary <string, object> result = JsonConvertX.DeserializeObject <Dictionary <string, object> >(json, new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
            });

            Assert.AreEqual(3, result.Count);
            Assert.AreEqual(1, ((JObject)result["Father"]).Count);
            Assert.AreEqual("blah!", (string)((JObject)result["Father"])["blah"]);
        }
        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);
        }
Exemplo n.º 16
0
        public void DeserializeFromJObject()
        {
            string json = @"
  {
    ""Value"": ""2017-12-05T21:59:00""
  }";

            JObject jo = JObject.Parse(json);

            DateTimeWrapper c1 = jo.ToObject <DateTimeWrapper>(JsonSerializer.Create(new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            }));

            DateTimeWrapper c2 = jo.ToObject <DateTimeWrapper>(JsonSerializer.Create(new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            }));

            DateTimeWrapper c3 = jo.ToObject <DateTimeWrapper>(JsonSerializer.Create(new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
            }));

            DateTimeWrapper c4 = jo.ToObject <DateTimeWrapper>();

            Assert.AreEqual(DateTimeKind.Utc, c1.Value.Kind);
            Assert.AreEqual(DateTimeKind.Local, c2.Value.Kind);
            Assert.AreEqual(DateTimeKind.Unspecified, c3.Value.Kind);
            Assert.AreEqual(DateTimeKind.Unspecified, c4.Value.Kind);
        }
        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);
        }
Exemplo n.º 18
0
        public void NullValueHandlingSerialization()
        {
            Store s1 = new Store();

            JsonSerializer jsonSerializer = new JsonSerializer();

            jsonSerializer.NullValueHandling = NullValueHandling.Ignore;

            StringWriter sw = new StringWriter();

            jsonSerializer.Serialize(sw, s1);

            //JsonConvertX.ConvertDateTimeToJavaScriptTicks(s1.Establised.DateTime)

            Assert.AreEqual(@"{""Color"":4,""Establised"":""2010-01-22T01:01:01Z"",""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""ExpiryDate"":""2000-02-02T23:01:30Z"",""Price"":0.0},{""Name"":""Alien"",""ExpiryDate"":""2000-01-01T00:00:00Z"",""Price"":0.0}]}", sw.GetStringBuilder().ToString());

            Store s2 = (Store)jsonSerializer.Deserialize(new JsonTextReader(new StringReader("{}")), typeof(Store));

            Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", s2.Escape);

            Store s3 = (Store)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(@"{""Escape"":null}")), typeof(Store));

            Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", s3.Escape);

            Store s4 = (Store)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(@"{""Color"":2,""Establised"":""\/Date(1264071600000+1300)\/"",""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""öäüÖÄÜ\\'{new Date(12345);}[222]_µ@²³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""ExpiryDate"":""\/Date(949485690000+1300)\/"",""Price"":0},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946638000000)\/"",""Price"":0.0}]}")), typeof(Store));

            Assert.AreEqual(s1.Establised, s3.Establised);
        }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
        public void ShouldSerializeTest()
        {
            ShouldSerializeTestClass c = new ShouldSerializeTestClass();

            c.Name = "James";
            c.Age  = 27;

            string json = JsonConvertX.SerializeObject(c, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""Age"": 27
}", json);

            c._shouldSerializeName = true;
            json = JsonConvertX.SerializeObject(c, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""Name"": ""James"",
  ""Age"": 27
}", json);

            ShouldSerializeTestClass deserialized = JsonConvertX.DeserializeObject <ShouldSerializeTestClass>(json);

            Assert.AreEqual("James", deserialized.Name);
            Assert.AreEqual(27, deserialized.Age);
        }
        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 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);
        }
        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 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 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);
        }
Exemplo n.º 26
0
        public void JTokenWriter_OverrideSpecifiedName()
        {
            JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();

            ignoreAttributeOnClassTestClass.Field = int.MinValue;

            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    OverrideSpecifiedNames = true
                }
            };

            JsonSerializer serializer = new JsonSerializer();

            serializer.ContractResolver = contractResolver;

            JTokenWriter writer = new JTokenWriter();

            serializer.Serialize(writer, ignoreAttributeOnClassTestClass);

            JObject   o = (JObject)writer.Token;
            JProperty p = o.Property("theField");

            Assert.IsNotNull(p);
            Assert.AreEqual(int.MinValue, (int)p.Value);
        }
        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 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 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);
        }
Exemplo n.º 30
0
        public static void AreEqual(string expected, string actual)
        {
            expected = Normalize(expected);
            actual   = Normalize(actual);

            Assert.AreEqual(expected, actual);
        }