Exemple #1
0
        public void SpecifiedTest()
        {
            SpecifiedTestClass c = new SpecifiedTestClass();

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

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

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

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

            Assert.IsNull(deserialized.Name);
            Assert.IsFalse(deserialized.NameSpecified);
            Assert.IsFalse(deserialized.WeightSpecified);
            Assert.IsFalse(deserialized.HeightSpecified);
            Assert.IsFalse(deserialized.FavoriteNumberSpecified);
            Assert.AreEqual(27, deserialized.Age);

            c.NameSpecified   = true;
            c.WeightSpecified = true;
            c.HeightSpecified = true;
            c.FavoriteNumber  = 23;
            json = JsonConvertX.SerializeObject(c, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""Name"": ""James"",
  ""Age"": 27,
  ""Weight"": 0,
  ""Height"": 0,
  ""FavoriteNumber"": 23
}", json);

            deserialized = JsonConvertX.DeserializeObject <SpecifiedTestClass>(json);
            Assert.AreEqual("James", deserialized.Name);
            Assert.IsTrue(deserialized.NameSpecified);
            Assert.IsTrue(deserialized.WeightSpecified);
            Assert.IsTrue(deserialized.HeightSpecified);
            Assert.IsTrue(deserialized.FavoriteNumberSpecified);
            Assert.AreEqual(27, deserialized.Age);
            Assert.AreEqual(23, deserialized.FavoriteNumber);
        }
        public void ErrorHandlingMetadata_TopLevel()
        {
            List <Exception> errors = new List <Exception>();

            JObject a2 = (JObject)JsonConvertX.DeserializeObject(@"{""$type"":""<Namespace>.JsonTest+MyTest2, <Assembly>""}", new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Error            = (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e) =>
                {
                    errors.Add(e.ErrorContext.Error);
                    e.ErrorContext.Handled = true;
                }
            });

            Assert.IsNull(a2);
            Assert.AreEqual(1, errors.Count);
            Assert.AreEqual("Error resolving type specified in JSON '<Namespace>.JsonTest+MyTest2, <Assembly>'. Path '$type', line 1, position 51.", errors[0].Message);
        }