-Line endings

This commit is contained in:
James Newton-King
2012-04-08 18:10:07 +12:00
parent a139d7bf20
commit 83618b1ea0
381 changed files with 96885 additions and 96885 deletions
@@ -1,224 +1,224 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
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 = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.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 = JsonConvert.SerializeObject(person, Formatting.Indented);
Assert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
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);
string json = o.ToString();
}
#if !NETFX_CORE
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.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));
}
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] {"Small", "Medium", "Large"}
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Assert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || WINDOWS_PHONE)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new DynamicTests.TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{"First", "Value1!"},
{"Second", "Value2!"}
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
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 = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.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 = JsonConvert.SerializeObject(person, Formatting.Indented);
Assert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
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);
string json = o.ToString();
}
#if !NETFX_CORE
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.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));
}
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] {"Small", "Medium", "Large"}
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Assert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || WINDOWS_PHONE)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new DynamicTests.TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{"First", "Value1!"},
{"Second", "Value2!"}
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
}
@@ -1,138 +1,138 @@
using System.Reflection;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class ConstructorHandlingTests : TestFixtureBase
{
[Test]
public void UsePrivateConstructorIfThereAreMultipleConstructorsWithParametersAndNothingToFallbackTo()
{
string json = @"{Name:""Name!""}";
var c = JsonConvert.DeserializeObject<PrivateConstructorTestClass>(json);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void SuccessWithPrivateConstructorAndAllowNonPublic()
{
string json = @"{Name:""Name!""}";
PrivateConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorTestClass>(json,
new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void FailWithPrivateConstructorPlusParametizedAndDefault()
{
ExceptionAssert.Throws<TargetInvocationException>(
null,
() =>
{
string json = @"{Name:""Name!""}";
PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
});
}
[Test]
public void SuccessWithPrivateConstructorPlusParametizedAndAllowNonPublic()
{
string json = @"{Name:""Name!""}";
PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json,
new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
Assert.AreEqual(1, c.Age);
}
[Test]
public void SuccessWithPublicParametizedConstructor()
{
string json = @"{Name:""Name!""}";
var c = JsonConvert.DeserializeObject<PublicParametizedConstructorTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterIsNotAProperty()
{
string json = @"{nameParameter:""Name!""}";
PublicParametizedConstructorWithNonPropertyParameterTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorWithNonPropertyParameterTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterRequiresAConverter()
{
string json = @"{nameParameter:""Name!""}";
PublicParametizedConstructorRequiringConverterTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorRequiringConverterTestClass>(json, new NameContainerConverter());
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name.Value);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterRequiresAConverterWithParameterAttribute()
{
string json = @"{nameParameter:""Name!""}";
PublicParametizedConstructorRequiringConverterWithParameterAttributeTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorRequiringConverterWithParameterAttributeTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name.Value);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterRequiresAConverterWithPropertyAttribute()
{
string json = @"{name:""Name!""}";
PublicParametizedConstructorRequiringConverterWithPropertyAttributeTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorRequiringConverterWithPropertyAttributeTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name.Value);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterNameConflictsWithPropertyName()
{
string json = @"{name:""1""}";
PublicParametizedConstructorWithPropertyNameConflict c = JsonConvert.DeserializeObject<PublicParametizedConstructorWithPropertyNameConflict>(json);
Assert.IsNotNull(c);
Assert.AreEqual(1, c.Name);
}
[Test]
public void PublicParametizedConstructorWithPropertyNameConflictWithAttribute()
{
string json = @"{name:""1""}";
PublicParametizedConstructorWithPropertyNameConflictWithAttribute c = JsonConvert.DeserializeObject<PublicParametizedConstructorWithPropertyNameConflictWithAttribute>(json);
Assert.IsNotNull(c);
Assert.AreEqual(1, c.Name);
}
}
using System.Reflection;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class ConstructorHandlingTests : TestFixtureBase
{
[Test]
public void UsePrivateConstructorIfThereAreMultipleConstructorsWithParametersAndNothingToFallbackTo()
{
string json = @"{Name:""Name!""}";
var c = JsonConvert.DeserializeObject<PrivateConstructorTestClass>(json);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void SuccessWithPrivateConstructorAndAllowNonPublic()
{
string json = @"{Name:""Name!""}";
PrivateConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorTestClass>(json,
new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void FailWithPrivateConstructorPlusParametizedAndDefault()
{
ExceptionAssert.Throws<TargetInvocationException>(
null,
() =>
{
string json = @"{Name:""Name!""}";
PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json);
});
}
[Test]
public void SuccessWithPrivateConstructorPlusParametizedAndAllowNonPublic()
{
string json = @"{Name:""Name!""}";
PrivateConstructorWithPublicParametizedConstructorTestClass c = JsonConvert.DeserializeObject<PrivateConstructorWithPublicParametizedConstructorTestClass>(json,
new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
});
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
Assert.AreEqual(1, c.Age);
}
[Test]
public void SuccessWithPublicParametizedConstructor()
{
string json = @"{Name:""Name!""}";
var c = JsonConvert.DeserializeObject<PublicParametizedConstructorTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterIsNotAProperty()
{
string json = @"{nameParameter:""Name!""}";
PublicParametizedConstructorWithNonPropertyParameterTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorWithNonPropertyParameterTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterRequiresAConverter()
{
string json = @"{nameParameter:""Name!""}";
PublicParametizedConstructorRequiringConverterTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorRequiringConverterTestClass>(json, new NameContainerConverter());
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name.Value);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterRequiresAConverterWithParameterAttribute()
{
string json = @"{nameParameter:""Name!""}";
PublicParametizedConstructorRequiringConverterWithParameterAttributeTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorRequiringConverterWithParameterAttributeTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name.Value);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterRequiresAConverterWithPropertyAttribute()
{
string json = @"{name:""Name!""}";
PublicParametizedConstructorRequiringConverterWithPropertyAttributeTestClass c = JsonConvert.DeserializeObject<PublicParametizedConstructorRequiringConverterWithPropertyAttributeTestClass>(json);
Assert.IsNotNull(c);
Assert.AreEqual("Name!", c.Name.Value);
}
[Test]
public void SuccessWithPublicParametizedConstructorWhenParamaterNameConflictsWithPropertyName()
{
string json = @"{name:""1""}";
PublicParametizedConstructorWithPropertyNameConflict c = JsonConvert.DeserializeObject<PublicParametizedConstructorWithPropertyNameConflict>(json);
Assert.IsNotNull(c);
Assert.AreEqual(1, c.Name);
}
[Test]
public void PublicParametizedConstructorWithPropertyNameConflictWithAttribute()
{
string json = @"{name:""1""}";
PublicParametizedConstructorWithPropertyNameConflictWithAttribute c = JsonConvert.DeserializeObject<PublicParametizedConstructorWithPropertyNameConflictWithAttribute>(json);
Assert.IsNotNull(c);
Assert.AreEqual(1, c.Name);
}
}
}
@@ -1,200 +1,200 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Serialization
{
public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
: base(false)
{
_startingWithChar = startingWithChar;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that start with the specified character
properties =
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
return properties;
}
}
public class Book
{
public string BookName { get; set; }
public decimal BookPrice { get; set; }
public string AuthorName { get; set; }
public int AuthorAge { get; set; }
public string AuthorCountry { get; set; }
}
public class IPersonContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(Employee))
objectType = typeof(IPerson);
return base.CreateContract(objectType);
}
}
public class AddressWithDataMember
{
[DataMember(Name = "CustomerAddress1")]
public string AddressLine1 { get; set; }
}
[TestFixture]
public class ContractResolverTests : TestFixtureBase
{
[Test]
public void DeserializeDataMemberClassWithNoDataContract()
{
var resolver = new DefaultContractResolver();
var contract = (JsonObjectContract)resolver.ResolveContract(typeof(AddressWithDataMember));
Assert.AreEqual("AddressLine1", contract.Properties[0].PropertyName);
}
[Test]
public void ResolveProperties_IgnoreStatic()
{
var resolver = new DefaultContractResolver();
var contract = (JsonObjectContract)resolver.ResolveContract(typeof(NumberFormatInfo));
Assert.IsFalse(contract.Properties.Any(c => c.PropertyName == "InvariantInfo"));
}
[Test]
public void SerializeInterface()
{
Employee employee = new Employee
{
BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc),
FirstName = "Maurice",
LastName = "Moss",
Department = "IT",
JobTitle = "Support"
};
string iPersonJson = JsonConvert.SerializeObject(employee, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new IPersonContractResolver() });
Assert.AreEqual(@"{
""FirstName"": ""Maurice"",
""LastName"": ""Moss"",
""BirthDate"": ""1977-12-30T01:01:01Z""
}", iPersonJson);
}
[Test]
public void SingleTypeWithMultipleContractResolvers()
{
Book book = new Book
{
BookName = "The Gathering Storm",
BookPrice = 16.19m,
AuthorName = "Brandon Sanderson",
AuthorAge = 34,
AuthorCountry = "United States of America"
};
string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
// {
// "AuthorName": "Brandon Sanderson",
// "AuthorAge": 34,
// "AuthorCountry": "United States of America"
// }
string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
// {
// "BookName": "The Gathering Storm",
// "BookPrice": 16.19
// }
Assert.AreEqual(@"{
""AuthorName"": ""Brandon Sanderson"",
""AuthorAge"": 34,
""AuthorCountry"": ""United States of America""
}", startingWithA);
Assert.AreEqual(@"{
""BookName"": ""The Gathering Storm"",
""BookPrice"": 16.19
}", startingWithB);
}
#if !NETFX_CORE
[Test]
public void SerializeCompilerGeneratedMembers()
{
StructTest structTest = new StructTest
{
IntField = 1,
IntProperty = 2,
StringField = "Field",
StringProperty = "Property"
};
DefaultContractResolver skipCompilerGeneratedResolver = new DefaultContractResolver
{
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public
};
string skipCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = skipCompilerGeneratedResolver });
Assert.AreEqual(@"{
""StringField"": ""Field"",
""IntField"": 1,
""StringProperty"": ""Property"",
""IntProperty"": 2
}", skipCompilerGeneratedJson);
DefaultContractResolver includeCompilerGeneratedResolver = new DefaultContractResolver
{
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
SerializeCompilerGeneratedMembers = true
};
string includeCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = includeCompilerGeneratedResolver });
Assert.AreEqual(@"{
""StringField"": ""Field"",
""IntField"": 1,
""<StringProperty>k__BackingField"": ""Property"",
""<IntProperty>k__BackingField"": 2,
""StringProperty"": ""Property"",
""IntProperty"": 2
}", includeCompilerGeneratedJson);
}
#endif
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Serialization
{
public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
: base(false)
{
_startingWithChar = startingWithChar;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that start with the specified character
properties =
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
return properties;
}
}
public class Book
{
public string BookName { get; set; }
public decimal BookPrice { get; set; }
public string AuthorName { get; set; }
public int AuthorAge { get; set; }
public string AuthorCountry { get; set; }
}
public class IPersonContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(Employee))
objectType = typeof(IPerson);
return base.CreateContract(objectType);
}
}
public class AddressWithDataMember
{
[DataMember(Name = "CustomerAddress1")]
public string AddressLine1 { get; set; }
}
[TestFixture]
public class ContractResolverTests : TestFixtureBase
{
[Test]
public void DeserializeDataMemberClassWithNoDataContract()
{
var resolver = new DefaultContractResolver();
var contract = (JsonObjectContract)resolver.ResolveContract(typeof(AddressWithDataMember));
Assert.AreEqual("AddressLine1", contract.Properties[0].PropertyName);
}
[Test]
public void ResolveProperties_IgnoreStatic()
{
var resolver = new DefaultContractResolver();
var contract = (JsonObjectContract)resolver.ResolveContract(typeof(NumberFormatInfo));
Assert.IsFalse(contract.Properties.Any(c => c.PropertyName == "InvariantInfo"));
}
[Test]
public void SerializeInterface()
{
Employee employee = new Employee
{
BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc),
FirstName = "Maurice",
LastName = "Moss",
Department = "IT",
JobTitle = "Support"
};
string iPersonJson = JsonConvert.SerializeObject(employee, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new IPersonContractResolver() });
Assert.AreEqual(@"{
""FirstName"": ""Maurice"",
""LastName"": ""Moss"",
""BirthDate"": ""1977-12-30T01:01:01Z""
}", iPersonJson);
}
[Test]
public void SingleTypeWithMultipleContractResolvers()
{
Book book = new Book
{
BookName = "The Gathering Storm",
BookPrice = 16.19m,
AuthorName = "Brandon Sanderson",
AuthorAge = 34,
AuthorCountry = "United States of America"
};
string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
// {
// "AuthorName": "Brandon Sanderson",
// "AuthorAge": 34,
// "AuthorCountry": "United States of America"
// }
string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
// {
// "BookName": "The Gathering Storm",
// "BookPrice": 16.19
// }
Assert.AreEqual(@"{
""AuthorName"": ""Brandon Sanderson"",
""AuthorAge"": 34,
""AuthorCountry"": ""United States of America""
}", startingWithA);
Assert.AreEqual(@"{
""BookName"": ""The Gathering Storm"",
""BookPrice"": 16.19
}", startingWithB);
}
#if !NETFX_CORE
[Test]
public void SerializeCompilerGeneratedMembers()
{
StructTest structTest = new StructTest
{
IntField = 1,
IntProperty = 2,
StringField = "Field",
StringProperty = "Property"
};
DefaultContractResolver skipCompilerGeneratedResolver = new DefaultContractResolver
{
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public
};
string skipCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = skipCompilerGeneratedResolver });
Assert.AreEqual(@"{
""StringField"": ""Field"",
""IntField"": 1,
""StringProperty"": ""Property"",
""IntProperty"": 2
}", skipCompilerGeneratedJson);
DefaultContractResolver includeCompilerGeneratedResolver = new DefaultContractResolver
{
DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
SerializeCompilerGeneratedMembers = true
};
string includeCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = includeCompilerGeneratedResolver });
Assert.AreEqual(@"{
""StringField"": ""Field"",
""IntField"": 1,
""<StringProperty>k__BackingField"": ""Property"",
""<IntProperty>k__BackingField"": 2,
""StringProperty"": ""Property"",
""IntProperty"": 2
}", includeCompilerGeneratedJson);
}
#endif
}
}
@@ -1,133 +1,133 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class DefaultValueHandlingTests : TestFixtureBase
{
[Test]
public void SerializeInvoice()
{
Invoice invoice = new Invoice
{
Company = "Acme Ltd.",
Amount = 50.0m,
Paid = false,
FollowUpDays = 30,
FollowUpEmailAddress = string.Empty,
PaidDate = null
};
string included = JsonConvert.SerializeObject(invoice,
Formatting.Indented,
new JsonSerializerSettings { });
// {
// "Company": "Acme Ltd.",
// "Amount": 50.0,
// "Paid": false,
// "PaidDate": null,
// "FollowUpDays": 30,
// "FollowUpEmailAddress": ""
// }
string ignored = JsonConvert.SerializeObject(invoice,
Formatting.Indented,
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
// {
// "Company": "Acme Ltd.",
// "Amount": 50.0
// }
Console.WriteLine(included);
Console.WriteLine(ignored);
}
[Test]
public void SerializeDefaultValueAttributeTest()
{
string json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass(),
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestField1"":0,""TestProperty1"":null}", json);
json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = int.MinValue, TestProperty1 = "NotDefault" },
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestField1"":-2147483648,""TestProperty1"":""NotDefault""}", json);
json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "NotDefault" },
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestProperty1"":""NotDefault""}", json);
json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "TestProperty1Value" },
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{}", json);
}
[Test]
public void DeserializeDefaultValueAttributeTest()
{
string json = "{}";
DefaultValueAttributeTestClass c = JsonConvert.DeserializeObject<DefaultValueAttributeTestClass>(json, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Populate
});
Assert.AreEqual("TestProperty1Value", c.TestProperty1);
c = JsonConvert.DeserializeObject<DefaultValueAttributeTestClass>(json, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
});
Assert.AreEqual("TestProperty1Value", c.TestProperty1);
}
[JsonObject]
public class NetworkUser
{
[JsonProperty(PropertyName = "userId")]
[DefaultValue(-1)]
public long GlobalId { get; set; }
[JsonProperty(PropertyName = "floatUserId")]
[DefaultValue(-1.0d)]
public float FloatGlobalId { get; set; }
[JsonProperty(PropertyName = "firstName")]
public string Firstname { get; set; }
[JsonProperty(PropertyName = "lastName")]
public string Lastname { get; set; }
public NetworkUser()
{
GlobalId = -1;
FloatGlobalId = -1.0f;
}
}
[Test]
public void IgnoreNumberTypeDifferencesWithDefaultValue()
{
NetworkUser user = new NetworkUser
{
Firstname = "blub"
};
string json = JsonConvert.SerializeObject(user, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
Assert.AreEqual(@"{""firstName"":""blub""}", json);
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class DefaultValueHandlingTests : TestFixtureBase
{
[Test]
public void SerializeInvoice()
{
Invoice invoice = new Invoice
{
Company = "Acme Ltd.",
Amount = 50.0m,
Paid = false,
FollowUpDays = 30,
FollowUpEmailAddress = string.Empty,
PaidDate = null
};
string included = JsonConvert.SerializeObject(invoice,
Formatting.Indented,
new JsonSerializerSettings { });
// {
// "Company": "Acme Ltd.",
// "Amount": 50.0,
// "Paid": false,
// "PaidDate": null,
// "FollowUpDays": 30,
// "FollowUpEmailAddress": ""
// }
string ignored = JsonConvert.SerializeObject(invoice,
Formatting.Indented,
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
// {
// "Company": "Acme Ltd.",
// "Amount": 50.0
// }
Console.WriteLine(included);
Console.WriteLine(ignored);
}
[Test]
public void SerializeDefaultValueAttributeTest()
{
string json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass(),
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestField1"":0,""TestProperty1"":null}", json);
json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = int.MinValue, TestProperty1 = "NotDefault" },
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestField1"":-2147483648,""TestProperty1"":""NotDefault""}", json);
json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "NotDefault" },
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{""TestProperty1"":""NotDefault""}", json);
json = JsonConvert.SerializeObject(new DefaultValueAttributeTestClass { TestField1 = 21, TestProperty1 = "TestProperty1Value" },
Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Assert.AreEqual(@"{}", json);
}
[Test]
public void DeserializeDefaultValueAttributeTest()
{
string json = "{}";
DefaultValueAttributeTestClass c = JsonConvert.DeserializeObject<DefaultValueAttributeTestClass>(json, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Populate
});
Assert.AreEqual("TestProperty1Value", c.TestProperty1);
c = JsonConvert.DeserializeObject<DefaultValueAttributeTestClass>(json, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
});
Assert.AreEqual("TestProperty1Value", c.TestProperty1);
}
[JsonObject]
public class NetworkUser
{
[JsonProperty(PropertyName = "userId")]
[DefaultValue(-1)]
public long GlobalId { get; set; }
[JsonProperty(PropertyName = "floatUserId")]
[DefaultValue(-1.0d)]
public float FloatGlobalId { get; set; }
[JsonProperty(PropertyName = "firstName")]
public string Firstname { get; set; }
[JsonProperty(PropertyName = "lastName")]
public string Lastname { get; set; }
public NetworkUser()
{
GlobalId = -1;
FloatGlobalId = -1.0f;
}
}
[Test]
public void IgnoreNumberTypeDifferencesWithDefaultValue()
{
NetworkUser user = new NetworkUser
{
Firstname = "blub"
};
string json = JsonConvert.SerializeObject(user, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
Assert.AreEqual(@"{""firstName"":""blub""}", json);
}
}
}
@@ -1,289 +1,289 @@
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters;
using System.Text;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class DynamicTests : TestFixtureBase
{
public class DynamicChildObject
{
public string Text { get; set; }
public int Integer { get; set; }
}
public class TestDynamicObject : DynamicObject
{
private readonly Dictionary<string, object> _members;
public int Int;
public DynamicChildObject ChildObject { get; set; }
internal Dictionary<string, object> Members
{
get { return _members; }
}
public TestDynamicObject()
{
_members = new Dictionary<string, object>();
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _members.Keys.Union(new[] { "Int", "ChildObject" });
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
Type targetType = binder.Type;
if (targetType == typeof(IDictionary<string, object>) ||
targetType == typeof(IDictionary))
{
result = new Dictionary<string, object>(_members);
return true;
}
else
{
return base.TryConvert(binder, out result);
}
}
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
return _members.Remove(binder.Name);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members[binder.Name] = value;
return true;
}
}
public class ErrorSettingDynamicObject : DynamicObject
{
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return false;
}
}
[Test]
public void SerializeDynamicObject()
{
TestDynamicObject dynamicObject = new TestDynamicObject();
dynamic d = dynamicObject;
d.Int = 1;
d.Decimal = 99.9d;
d.ChildObject = new DynamicChildObject();
Dictionary<string, object> values = new Dictionary<string, object>();
foreach (string memberName in dynamicObject.GetDynamicMemberNames())
{
object value;
dynamicObject.TryGetMember(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);
Assert.AreEqual(@"{
""Decimal"": 99.9,
""Int"": 1,
""ChildObject"": {
""Text"": null,
""Integer"": 0
}
}", json);
TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject<TestDynamicObject>(json);
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);
}
[Test]
public void SerializeDynamicObjectWithObjectTracking()
{
dynamic o = new ExpandoObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
o.DynamicChildObject = new DynamicChildObject
{
Integer = int.MinValue,
Text = "Child text!"
};
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
});
Console.WriteLine(json);
string dynamicChildObjectTypeName = ReflectionUtils.GetTypeName(typeof(DynamicChildObject), FormatterAssemblyStyle.Full);
string expandoObjectTypeName = ReflectionUtils.GetTypeName(typeof(ExpandoObject), FormatterAssemblyStyle.Full);
Assert.AreEqual(@"{
""$type"": """ + expandoObjectTypeName + @""",
""Text"": ""Text!"",
""Integer"": 2147483647,
""DynamicChildObject"": {
""$type"": """ + dynamicChildObjectTypeName + @""",
""Text"": ""Child text!"",
""Integer"": -2147483648
}
}", json);
dynamic n = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
});
CustomAssert.IsInstanceOfType(typeof(ExpandoObject), n);
Assert.AreEqual("Text!", n.Text);
Assert.AreEqual(int.MaxValue, n.Integer);
CustomAssert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject);
Assert.AreEqual("Child text!", n.DynamicChildObject.Text);
Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer);
}
[Test]
public void NoPublicDefaultConstructor()
{
ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.",
() =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var json = @"{
""contributors"": null
}";
JsonConvert.DeserializeObject<DynamicObject>(json, settings);
});
}
public class DictionaryDynamicObject : DynamicObject
{
public IDictionary<string, object> Values { get; private set; }
protected DictionaryDynamicObject()
{
Values = new Dictionary<string, object>();
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Values[binder.Name] = value;
return true;
}
}
[Test]
public void AllowNonPublicDefaultConstructor()
{
var settings = new JsonSerializerSettings();
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
var json = @"{
""contributors"": null,
""retweeted"": false,
""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
""in_reply_to_user_id_str"": null,
""retweet_count"": 0,
""geo"": null,
""id_str"": ""40678260320768000"",
""in_reply_to_status_id"": null,
""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
""place"": null,
""coordinates"": null,
""truncated"": false,
""favorited"": false,
""user"": {
""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
""url"": ""http://bit.ly/dcFwWC"",
""screen_name"": ""marutisuzukisx4"",
""verified"": false,
""friends_count"": 45,
""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
""follow_request_sent"": null,
""time_zone"": ""Chennai"",
""profile_text_color"": ""333333"",
""location"": ""India"",
""notifications"": null,
""profile_sidebar_fill_color"": ""efefef"",
""id_str"": ""196143889"",
""contributors_enabled"": false,
""lang"": ""en"",
""profile_background_tile"": false,
""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
""followers_count"": 117,
""show_all_inline_media"": true,
""listed_count"": 1,
""geo_enabled"": true,
""profile_link_color"": ""009999"",
""profile_sidebar_border_color"": ""eeeeee"",
""protected"": false,
""name"": ""Maruti Suzuki SX4"",
""statuses_count"": 637,
""following"": null,
""profile_use_background_image"": true,
""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
""id"": 196143889,
""is_translator"": false,
""utc_offset"": 19800,
""favourites_count"": 0,
""profile_background_color"": ""131516""
},
""in_reply_to_screen_name"": null,
""id"": 40678260320768000,
""in_reply_to_status_id_str"": null,
""in_reply_to_user_id"": null
}";
DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);
Assert.AreEqual(false, foo.Values["retweeted"]);
}
}
}
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters;
using System.Text;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class DynamicTests : TestFixtureBase
{
public class DynamicChildObject
{
public string Text { get; set; }
public int Integer { get; set; }
}
public class TestDynamicObject : DynamicObject
{
private readonly Dictionary<string, object> _members;
public int Int;
public DynamicChildObject ChildObject { get; set; }
internal Dictionary<string, object> Members
{
get { return _members; }
}
public TestDynamicObject()
{
_members = new Dictionary<string, object>();
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _members.Keys.Union(new[] { "Int", "ChildObject" });
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
Type targetType = binder.Type;
if (targetType == typeof(IDictionary<string, object>) ||
targetType == typeof(IDictionary))
{
result = new Dictionary<string, object>(_members);
return true;
}
else
{
return base.TryConvert(binder, out result);
}
}
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
return _members.Remove(binder.Name);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members[binder.Name] = value;
return true;
}
}
public class ErrorSettingDynamicObject : DynamicObject
{
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return false;
}
}
[Test]
public void SerializeDynamicObject()
{
TestDynamicObject dynamicObject = new TestDynamicObject();
dynamic d = dynamicObject;
d.Int = 1;
d.Decimal = 99.9d;
d.ChildObject = new DynamicChildObject();
Dictionary<string, object> values = new Dictionary<string, object>();
foreach (string memberName in dynamicObject.GetDynamicMemberNames())
{
object value;
dynamicObject.TryGetMember(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);
Assert.AreEqual(@"{
""Decimal"": 99.9,
""Int"": 1,
""ChildObject"": {
""Text"": null,
""Integer"": 0
}
}", json);
TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject<TestDynamicObject>(json);
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);
}
[Test]
public void SerializeDynamicObjectWithObjectTracking()
{
dynamic o = new ExpandoObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
o.DynamicChildObject = new DynamicChildObject
{
Integer = int.MinValue,
Text = "Child text!"
};
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
});
Console.WriteLine(json);
string dynamicChildObjectTypeName = ReflectionUtils.GetTypeName(typeof(DynamicChildObject), FormatterAssemblyStyle.Full);
string expandoObjectTypeName = ReflectionUtils.GetTypeName(typeof(ExpandoObject), FormatterAssemblyStyle.Full);
Assert.AreEqual(@"{
""$type"": """ + expandoObjectTypeName + @""",
""Text"": ""Text!"",
""Integer"": 2147483647,
""DynamicChildObject"": {
""$type"": """ + dynamicChildObjectTypeName + @""",
""Text"": ""Child text!"",
""Integer"": -2147483648
}
}", json);
dynamic n = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
});
CustomAssert.IsInstanceOfType(typeof(ExpandoObject), n);
Assert.AreEqual("Text!", n.Text);
Assert.AreEqual(int.MaxValue, n.Integer);
CustomAssert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject);
Assert.AreEqual("Child text!", n.DynamicChildObject.Text);
Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer);
}
[Test]
public void NoPublicDefaultConstructor()
{
ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.",
() =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var json = @"{
""contributors"": null
}";
JsonConvert.DeserializeObject<DynamicObject>(json, settings);
});
}
public class DictionaryDynamicObject : DynamicObject
{
public IDictionary<string, object> Values { get; private set; }
protected DictionaryDynamicObject()
{
Values = new Dictionary<string, object>();
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Values[binder.Name] = value;
return true;
}
}
[Test]
public void AllowNonPublicDefaultConstructor()
{
var settings = new JsonSerializerSettings();
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
var json = @"{
""contributors"": null,
""retweeted"": false,
""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
""in_reply_to_user_id_str"": null,
""retweet_count"": 0,
""geo"": null,
""id_str"": ""40678260320768000"",
""in_reply_to_status_id"": null,
""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
""place"": null,
""coordinates"": null,
""truncated"": false,
""favorited"": false,
""user"": {
""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
""url"": ""http://bit.ly/dcFwWC"",
""screen_name"": ""marutisuzukisx4"",
""verified"": false,
""friends_count"": 45,
""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
""follow_request_sent"": null,
""time_zone"": ""Chennai"",
""profile_text_color"": ""333333"",
""location"": ""India"",
""notifications"": null,
""profile_sidebar_fill_color"": ""efefef"",
""id_str"": ""196143889"",
""contributors_enabled"": false,
""lang"": ""en"",
""profile_background_tile"": false,
""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
""followers_count"": 117,
""show_all_inline_media"": true,
""listed_count"": 1,
""geo_enabled"": true,
""profile_link_color"": ""009999"",
""profile_sidebar_border_color"": ""eeeeee"",
""protected"": false,
""name"": ""Maruti Suzuki SX4"",
""statuses_count"": 637,
""following"": null,
""profile_use_background_image"": true,
""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
""id"": 196143889,
""is_translator"": false,
""utc_offset"": 19800,
""favourites_count"": 0,
""profile_background_color"": ""131516""
},
""in_reply_to_screen_name"": null,
""id"": 40678260320768000,
""in_reply_to_status_id_str"": null,
""in_reply_to_user_id"": null
}";
DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);
Assert.AreEqual(false, foo.Values["retweeted"]);
}
}
}
#endif
@@ -1,321 +1,321 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET35 || NET20 || SILVERLIGHT || NETFX_CORE)
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class EntitiesSerializationTests : TestFixtureBase
{
[Test]
public void SerializeEntity()
{
Folder rootFolder = CreateEntitiesTestData();
string json = JsonConvert.SerializeObject(rootFolder, Formatting.Indented, new IsoDateTimeConverter());
string expected = @"{
""$id"": ""1"",
""FolderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
""Name"": ""Root folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2000-12-10T10:50:00Z"",
""Files"": [],
""ChildFolders"": [
{
""$id"": ""2"",
""FolderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
""Name"": ""Child folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2001-11-20T10:50:00Z"",
""Files"": [
{
""$id"": ""3"",
""FileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
""Name"": ""File 1"",
""Description"": ""Description!"",
""CreatedDate"": ""2002-10-30T10:50:00Z"",
""Folder"": {
""$ref"": ""2""
},
""EntityKey"": {
""$id"": ""4"",
""EntitySetName"": ""File"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FileId"",
""Type"": ""System.Guid"",
""Value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
}
]
}
}
],
""ChildFolders"": [],
""ParentFolder"": {
""$ref"": ""1""
},
""EntityKey"": {
""$id"": ""5"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
}
]
}
}
],
""ParentFolder"": null,
""EntityKey"": {
""$id"": ""6"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
}
]
}
}";
Assert.AreEqual(expected, json);
}
[Test]
public void DeserializeEntity()
{
string json = @"{
""$id"": ""1"",
""FolderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
""Name"": ""Root folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2000-12-10T10:50:00Z"",
""Files"": [],
""ChildFolders"": [
{
""$id"": ""2"",
""FolderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
""Name"": ""Child folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2001-11-20T10:50:00Z"",
""Files"": [
{
""$id"": ""3"",
""FileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
""Name"": ""File 1"",
""Description"": ""Description!"",
""CreatedDate"": ""2002-10-30T10:50:00Z"",
""Folder"": {
""$ref"": ""2""
},
""EntityKey"": {
""$id"": ""4"",
""EntitySetName"": ""File"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FileId"",
""Type"": ""System.Guid"",
""Value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
}
]
}
}
],
""ChildFolders"": [],
""ParentFolder"": {
""$ref"": ""1""
},
""EntityKey"": {
""$id"": ""5"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
}
]
}
}
],
""ParentFolder"": null,
""EntityKey"": {
""$id"": ""6"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
}
]
}
}";
Folder f = JsonConvert.DeserializeObject<Folder>(json, new IsoDateTimeConverter());
Assert.IsNotNull(f);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), f.FolderId);
Assert.AreEqual("Folder", f.EntityKey.EntitySetName);
Assert.AreEqual("DataServicesTestDatabaseEntities", f.EntityKey.EntityContainerName);
Assert.AreEqual("Folder", f.EntityKey.EntitySetName);
Assert.AreEqual(false, f.EntityKey.IsTemporary);
Assert.AreEqual(1, f.EntityKey.EntityKeyValues.Length);
Assert.AreEqual("FolderId", f.EntityKey.EntityKeyValues[0].Key);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), f.EntityKey.EntityKeyValues[0].Value);
Assert.AreEqual("Root folder", f.Name);
Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), f.CreatedDate);
Assert.AreEqual(null, f.ParentFolder);
Assert.AreEqual(1, f.ChildFolders.Count);
Folder childFolder = f.ChildFolders.ElementAt(0);
Assert.AreEqual("Child folder", childFolder.Name);
Assert.AreEqual("Description!", childFolder.Description);
Assert.AreEqual(f, childFolder.ParentFolder);
Assert.AreEqual(f, childFolder.ParentFolderReference.Value);
// is this a problem?
Assert.AreEqual(null, childFolder.ParentFolderReference.EntityKey);
}
[Test]
public void SerializeMultiValueEntityKey()
{
EntityKey e = new EntityKey("DataServicesTestDatabaseEntities.Folder",
new List<EntityKeyMember>
{
new EntityKeyMember("GuidId", new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E")),
new EntityKeyMember("IntId", int.MaxValue),
new EntityKeyMember("LongId", long.MaxValue),
new EntityKeyMember("StringId", "String!"),
new EntityKeyMember("DateTimeId", new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc))
});
string json = JsonConvert.SerializeObject(e, Formatting.Indented);
Assert.AreEqual(@"{
""$id"": ""1"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""GuidId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
},
{
""Key"": ""IntId"",
""Type"": ""System.Int32"",
""Value"": ""2147483647""
},
{
""Key"": ""LongId"",
""Type"": ""System.Int64"",
""Value"": ""9223372036854775807""
},
{
""Key"": ""StringId"",
""Type"": ""System.String"",
""Value"": ""String!""
},
{
""Key"": ""DateTimeId"",
""Type"": ""System.DateTime"",
""Value"": ""12/10/2000 10:50:00""
}
]
}", json);
EntityKey newKey = JsonConvert.DeserializeObject<EntityKey>(json);
Assert.IsFalse(ReferenceEquals(e, newKey));
Assert.AreEqual(5, newKey.EntityKeyValues.Length);
Assert.AreEqual("GuidId", newKey.EntityKeyValues[0].Key);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), newKey.EntityKeyValues[0].Value);
Assert.AreEqual("IntId", newKey.EntityKeyValues[1].Key);
Assert.AreEqual(int.MaxValue, newKey.EntityKeyValues[1].Value);
Assert.AreEqual("LongId", newKey.EntityKeyValues[2].Key);
Assert.AreEqual(long.MaxValue, newKey.EntityKeyValues[2].Value);
Assert.AreEqual("StringId", newKey.EntityKeyValues[3].Key);
Assert.AreEqual("String!", newKey.EntityKeyValues[3].Value);
Assert.AreEqual("DateTimeId", newKey.EntityKeyValues[4].Key);
Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), newKey.EntityKeyValues[4].Value);
}
private Folder CreateEntitiesTestData()
{
Folder folder = new Folder();
folder.FolderId = new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E");
folder.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.Folder", "FolderId", folder.FolderId);
folder.Name = "Root folder";
folder.Description = "Description!";
folder.CreatedDate = new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc);
Folder childFolder = new Folder();
childFolder.FolderId = new Guid("484936E2-7CBB-4592-93FF-B2103E5705E4");
childFolder.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.Folder", "FolderId", childFolder.FolderId);
childFolder.Name = "Child folder";
childFolder.Description = "Description!";
childFolder.CreatedDate = new DateTime(2001, 11, 20, 10, 50, 0, DateTimeKind.Utc);
folder.ChildFolders.Add(childFolder);
File file1 = new File();
file1.FileId = new Guid("CC76D734-49F1-4616-BB38-41514228AC6C");
file1.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.File", "FileId", file1.FileId);
file1.Name = "File 1";
file1.Description = "Description!";
file1.CreatedDate = new DateTime(2002, 10, 30, 10, 50, 0, DateTimeKind.Utc);
childFolder.Files.Add(file1);
return folder;
}
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET35 || NET20 || SILVERLIGHT || NETFX_CORE)
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class EntitiesSerializationTests : TestFixtureBase
{
[Test]
public void SerializeEntity()
{
Folder rootFolder = CreateEntitiesTestData();
string json = JsonConvert.SerializeObject(rootFolder, Formatting.Indented, new IsoDateTimeConverter());
string expected = @"{
""$id"": ""1"",
""FolderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
""Name"": ""Root folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2000-12-10T10:50:00Z"",
""Files"": [],
""ChildFolders"": [
{
""$id"": ""2"",
""FolderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
""Name"": ""Child folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2001-11-20T10:50:00Z"",
""Files"": [
{
""$id"": ""3"",
""FileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
""Name"": ""File 1"",
""Description"": ""Description!"",
""CreatedDate"": ""2002-10-30T10:50:00Z"",
""Folder"": {
""$ref"": ""2""
},
""EntityKey"": {
""$id"": ""4"",
""EntitySetName"": ""File"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FileId"",
""Type"": ""System.Guid"",
""Value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
}
]
}
}
],
""ChildFolders"": [],
""ParentFolder"": {
""$ref"": ""1""
},
""EntityKey"": {
""$id"": ""5"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
}
]
}
}
],
""ParentFolder"": null,
""EntityKey"": {
""$id"": ""6"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
}
]
}
}";
Assert.AreEqual(expected, json);
}
[Test]
public void DeserializeEntity()
{
string json = @"{
""$id"": ""1"",
""FolderId"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e"",
""Name"": ""Root folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2000-12-10T10:50:00Z"",
""Files"": [],
""ChildFolders"": [
{
""$id"": ""2"",
""FolderId"": ""484936e2-7cbb-4592-93ff-b2103e5705e4"",
""Name"": ""Child folder"",
""Description"": ""Description!"",
""CreatedDate"": ""2001-11-20T10:50:00Z"",
""Files"": [
{
""$id"": ""3"",
""FileId"": ""cc76d734-49f1-4616-bb38-41514228ac6c"",
""Name"": ""File 1"",
""Description"": ""Description!"",
""CreatedDate"": ""2002-10-30T10:50:00Z"",
""Folder"": {
""$ref"": ""2""
},
""EntityKey"": {
""$id"": ""4"",
""EntitySetName"": ""File"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FileId"",
""Type"": ""System.Guid"",
""Value"": ""cc76d734-49f1-4616-bb38-41514228ac6c""
}
]
}
}
],
""ChildFolders"": [],
""ParentFolder"": {
""$ref"": ""1""
},
""EntityKey"": {
""$id"": ""5"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""484936e2-7cbb-4592-93ff-b2103e5705e4""
}
]
}
}
],
""ParentFolder"": null,
""EntityKey"": {
""$id"": ""6"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""FolderId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
}
]
}
}";
Folder f = JsonConvert.DeserializeObject<Folder>(json, new IsoDateTimeConverter());
Assert.IsNotNull(f);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), f.FolderId);
Assert.AreEqual("Folder", f.EntityKey.EntitySetName);
Assert.AreEqual("DataServicesTestDatabaseEntities", f.EntityKey.EntityContainerName);
Assert.AreEqual("Folder", f.EntityKey.EntitySetName);
Assert.AreEqual(false, f.EntityKey.IsTemporary);
Assert.AreEqual(1, f.EntityKey.EntityKeyValues.Length);
Assert.AreEqual("FolderId", f.EntityKey.EntityKeyValues[0].Key);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), f.EntityKey.EntityKeyValues[0].Value);
Assert.AreEqual("Root folder", f.Name);
Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), f.CreatedDate);
Assert.AreEqual(null, f.ParentFolder);
Assert.AreEqual(1, f.ChildFolders.Count);
Folder childFolder = f.ChildFolders.ElementAt(0);
Assert.AreEqual("Child folder", childFolder.Name);
Assert.AreEqual("Description!", childFolder.Description);
Assert.AreEqual(f, childFolder.ParentFolder);
Assert.AreEqual(f, childFolder.ParentFolderReference.Value);
// is this a problem?
Assert.AreEqual(null, childFolder.ParentFolderReference.EntityKey);
}
[Test]
public void SerializeMultiValueEntityKey()
{
EntityKey e = new EntityKey("DataServicesTestDatabaseEntities.Folder",
new List<EntityKeyMember>
{
new EntityKeyMember("GuidId", new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E")),
new EntityKeyMember("IntId", int.MaxValue),
new EntityKeyMember("LongId", long.MaxValue),
new EntityKeyMember("StringId", "String!"),
new EntityKeyMember("DateTimeId", new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc))
});
string json = JsonConvert.SerializeObject(e, Formatting.Indented);
Assert.AreEqual(@"{
""$id"": ""1"",
""EntitySetName"": ""Folder"",
""EntityContainerName"": ""DataServicesTestDatabaseEntities"",
""EntityKeyValues"": [
{
""Key"": ""GuidId"",
""Type"": ""System.Guid"",
""Value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
},
{
""Key"": ""IntId"",
""Type"": ""System.Int32"",
""Value"": ""2147483647""
},
{
""Key"": ""LongId"",
""Type"": ""System.Int64"",
""Value"": ""9223372036854775807""
},
{
""Key"": ""StringId"",
""Type"": ""System.String"",
""Value"": ""String!""
},
{
""Key"": ""DateTimeId"",
""Type"": ""System.DateTime"",
""Value"": ""12/10/2000 10:50:00""
}
]
}", json);
EntityKey newKey = JsonConvert.DeserializeObject<EntityKey>(json);
Assert.IsFalse(ReferenceEquals(e, newKey));
Assert.AreEqual(5, newKey.EntityKeyValues.Length);
Assert.AreEqual("GuidId", newKey.EntityKeyValues[0].Key);
Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), newKey.EntityKeyValues[0].Value);
Assert.AreEqual("IntId", newKey.EntityKeyValues[1].Key);
Assert.AreEqual(int.MaxValue, newKey.EntityKeyValues[1].Value);
Assert.AreEqual("LongId", newKey.EntityKeyValues[2].Key);
Assert.AreEqual(long.MaxValue, newKey.EntityKeyValues[2].Value);
Assert.AreEqual("StringId", newKey.EntityKeyValues[3].Key);
Assert.AreEqual("String!", newKey.EntityKeyValues[3].Value);
Assert.AreEqual("DateTimeId", newKey.EntityKeyValues[4].Key);
Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), newKey.EntityKeyValues[4].Value);
}
private Folder CreateEntitiesTestData()
{
Folder folder = new Folder();
folder.FolderId = new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E");
folder.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.Folder", "FolderId", folder.FolderId);
folder.Name = "Root folder";
folder.Description = "Description!";
folder.CreatedDate = new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc);
Folder childFolder = new Folder();
childFolder.FolderId = new Guid("484936E2-7CBB-4592-93FF-B2103E5705E4");
childFolder.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.Folder", "FolderId", childFolder.FolderId);
childFolder.Name = "Child folder";
childFolder.Description = "Description!";
childFolder.CreatedDate = new DateTime(2001, 11, 20, 10, 50, 0, DateTimeKind.Utc);
folder.ChildFolders.Add(childFolder);
File file1 = new File();
file1.FileId = new Guid("CC76D734-49F1-4616-BB38-41514228AC6C");
file1.EntityKey = new EntityKey("DataServicesTestDatabaseEntities.File", "FileId", file1.FileId);
file1.Name = "File 1";
file1.Description = "Description!";
file1.CreatedDate = new DateTime(2002, 10, 30, 10, 50, 0, DateTimeKind.Utc);
childFolder.Files.Add(file1);
return folder;
}
}
}
#endif
@@ -1,60 +1,60 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class JsonPropertyCollectionTests : TestFixtureBase
{
[Test]
public void AddPropertyIncludesPrivateImplementations()
{
var value = new PrivateImplementationBClass
{
OverriddenProperty = "OverriddenProperty",
PropertyA = "PropertyA",
PropertyB = "PropertyB"
};
var resolver = new DefaultContractResolver();
var contract = (JsonObjectContract) resolver.ResolveContract(value.GetType());
Assert.AreEqual(3, contract.Properties.Count);
Assert.IsTrue(contract.Properties.Contains("OverriddenProperty"), "Contract is missing property 'OverriddenProperty'");
Assert.IsTrue(contract.Properties.Contains("PropertyA"), "Contract is missing property 'PropertyA'");
Assert.IsTrue(contract.Properties.Contains("PropertyB"), "Contract is missing property 'PropertyB'");
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class JsonPropertyCollectionTests : TestFixtureBase
{
[Test]
public void AddPropertyIncludesPrivateImplementations()
{
var value = new PrivateImplementationBClass
{
OverriddenProperty = "OverriddenProperty",
PropertyA = "PropertyA",
PropertyB = "PropertyB"
};
var resolver = new DefaultContractResolver();
var contract = (JsonObjectContract) resolver.ResolveContract(value.GetType());
Assert.AreEqual(3, contract.Properties.Count);
Assert.IsTrue(contract.Properties.Contains("OverriddenProperty"), "Contract is missing property 'OverriddenProperty'");
Assert.IsTrue(contract.Properties.Contains("PropertyA"), "Contract is missing property 'PropertyA'");
Assert.IsTrue(contract.Properties.Contains("PropertyB"), "Contract is missing property 'PropertyB'");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,152 +1,152 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class MissingMemberHandlingTests : TestFixtureBase
{
[Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11."
#endif
)]
public void MissingMemberDeserialize()
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product, Formatting.Indented);
//{
// "Name": "Apple",
// "ExpiryDate": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error });
}
[Test]
public void MissingMemberDeserializeOkay()
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.MissingMemberHandling = MissingMemberHandling.Ignore;
object deserializedValue;
using (JsonReader jsonReader = new JsonTextReader(new StringReader(output)))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, typeof(ProductShort));
}
ProductShort deserializedProductShort = (ProductShort)deserializedValue;
Assert.AreEqual("Apple", deserializedProductShort.Name);
Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProductShort.ExpiryDate);
Assert.AreEqual("Small", deserializedProductShort.Sizes[0]);
Assert.AreEqual("Medium", deserializedProductShort.Sizes[1]);
Assert.AreEqual("Large", deserializedProductShort.Sizes[2]);
}
[Test]
public void MissingMemberIgnoreComplexValue()
{
JsonSerializer serializer = new JsonSerializer { MissingMemberHandling = MissingMemberHandling.Ignore };
serializer.Converters.Add(new JavaScriptDateTimeConverter());
string response = @"{""PreProperty"":1,""DateProperty"":new Date(1225962698973),""PostProperty"":2}";
MyClass myClass = (MyClass)serializer.Deserialize(new StringReader(response), typeof(MyClass));
Assert.AreEqual(1, myClass.PreProperty);
Assert.AreEqual(2, myClass.PostProperty);
}
[Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11."
#endif
)]
public void MissingMemeber()
{
string json = @"{""Missing"":1}";
JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error });
}
[Test]
public void MissingJson()
{
string json = @"{}";
JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error
});
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class MissingMemberHandlingTests : TestFixtureBase
{
[Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11."
#endif
)]
public void MissingMemberDeserialize()
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product, Formatting.Indented);
//{
// "Name": "Apple",
// "ExpiryDate": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error });
}
[Test]
public void MissingMemberDeserializeOkay()
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.MissingMemberHandling = MissingMemberHandling.Ignore;
object deserializedValue;
using (JsonReader jsonReader = new JsonTextReader(new StringReader(output)))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, typeof(ProductShort));
}
ProductShort deserializedProductShort = (ProductShort)deserializedValue;
Assert.AreEqual("Apple", deserializedProductShort.Name);
Assert.AreEqual(new DateTime(2008, 12, 28), deserializedProductShort.ExpiryDate);
Assert.AreEqual("Small", deserializedProductShort.Sizes[0]);
Assert.AreEqual("Medium", deserializedProductShort.Sizes[1]);
Assert.AreEqual("Large", deserializedProductShort.Sizes[2]);
}
[Test]
public void MissingMemberIgnoreComplexValue()
{
JsonSerializer serializer = new JsonSerializer { MissingMemberHandling = MissingMemberHandling.Ignore };
serializer.Converters.Add(new JavaScriptDateTimeConverter());
string response = @"{""PreProperty"":1,""DateProperty"":new Date(1225962698973),""PostProperty"":2}";
MyClass myClass = (MyClass)serializer.Deserialize(new StringReader(response), typeof(MyClass));
Assert.AreEqual(1, myClass.PreProperty);
Assert.AreEqual(2, myClass.PostProperty);
}
[Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11."
#endif
)]
public void MissingMemeber()
{
string json = @"{""Missing"":1}";
JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error });
}
[Test]
public void MissingJson()
{
string json = @"{}";
JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error
});
}
}
}
@@ -1,128 +1,128 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class NullValueHandlingTests : TestFixtureBase
{
[Test]
public void DeserializeNullIntoDateTime()
{
DateTimeTestClass c = JsonConvert.DeserializeObject<DateTimeTestClass>(@"{DateTimeField:null}", new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Assert.AreEqual(c.DateTimeField, default(DateTime));
}
[Test]
public void DeserializeEmptyStringIntoDateTimeWithEmptyStringDefaultValue()
{
DateTimeTestClass c = JsonConvert.DeserializeObject<DateTimeTestClass>(@"{DateTimeField:""""}", new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Assert.AreEqual(c.DateTimeField, default(DateTime));
}
[Test]
public void NullValueHandlingSerialization()
{
Store s1 = new Store();
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
StringWriter sw = new StringWriter();
jsonSerializer.Serialize(sw, s1);
//JsonConvert.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);
}
[Test]
public void NullValueHandlingBlogPost()
{
Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";
string included = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { });
// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys",
// "Classification": null,
// "Studio": null,
// "ReleaseDate": null,
// "ReleaseCountries": null
// }
string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys"
// }
Assert.AreEqual(@"{
""Name"": ""Bad Boys III"",
""Description"": ""It's no Bad Boys"",
""Classification"": null,
""Studio"": null,
""ReleaseDate"": null,
""ReleaseCountries"": null
}", included);
Assert.AreEqual(@"{
""Name"": ""Bad Boys III"",
""Description"": ""It's no Bad Boys""
}", ignored);
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class NullValueHandlingTests : TestFixtureBase
{
[Test]
public void DeserializeNullIntoDateTime()
{
DateTimeTestClass c = JsonConvert.DeserializeObject<DateTimeTestClass>(@"{DateTimeField:null}", new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Assert.AreEqual(c.DateTimeField, default(DateTime));
}
[Test]
public void DeserializeEmptyStringIntoDateTimeWithEmptyStringDefaultValue()
{
DateTimeTestClass c = JsonConvert.DeserializeObject<DateTimeTestClass>(@"{DateTimeField:""""}", new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Assert.AreEqual(c.DateTimeField, default(DateTime));
}
[Test]
public void NullValueHandlingSerialization()
{
Store s1 = new Store();
JsonSerializer jsonSerializer = new JsonSerializer();
jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
StringWriter sw = new StringWriter();
jsonSerializer.Serialize(sw, s1);
//JsonConvert.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);
}
[Test]
public void NullValueHandlingBlogPost()
{
Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";
string included = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { });
// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys",
// "Classification": null,
// "Studio": null,
// "ReleaseDate": null,
// "ReleaseCountries": null
// }
string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys"
// }
Assert.AreEqual(@"{
""Name"": ""Bad Boys III"",
""Description"": ""It's no Bad Boys"",
""Classification"": null,
""Studio"": null,
""ReleaseDate"": null,
""ReleaseCountries"": null
}", included);
Assert.AreEqual(@"{
""Name"": ""Bad Boys III"",
""Description"": ""It's no Bad Boys""
}", ignored);
}
}
}
@@ -1,150 +1,150 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class PopulateTests : TestFixtureBase
{
[Test]
public void PopulatePerson()
{
Person p = new Person();
JsonConvert.PopulateObject(@"{""Name"":""James""}", p);
Assert.AreEqual("James", p.Name);
}
[Test]
public void PopulateStore()
{
Store s = new Store();
s.Color = StoreColor.Red;
s.product = new List<Product>
{
new Product
{
ExpiryDate = new DateTime(2000, 12, 3, 0, 0, 0, DateTimeKind.Utc),
Name = "ProductName!",
Price = 9.9m
}
};
s.Width = 99.99d;
s.Mottos = new List<string> { "Can do!", "We deliver!" };
string json = @"{
""Color"": 2,
""Establised"": ""\/Date(1264122061000+0000)\/"",
""Width"": 99.99,
""Employees"": 999,
""RoomsPerFloor"": [
1,
2,
3,
4,
5,
6,
7,
8,
9
],
""Open"": false,
""Symbol"": ""@"",
""Mottos"": [
""Fail whale""
],
""Cost"": 100980.1,
""Escape"": ""\r\n\t\f\b?{\\r\\n\""'"",
""product"": [
{
""Name"": ""ProductName!"",
""ExpiryDate"": ""\/Date(975801600000)\/"",
""Price"": 9.9,
""Sizes"": null
}
]
}";
JsonConvert.PopulateObject(json, s, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
Assert.AreEqual(1, s.Mottos.Count);
Assert.AreEqual("Fail whale", s.Mottos[0]);
Assert.AreEqual(1, s.product.Count);
//Assert.AreEqual("James", p.Name);
}
[Test]
public void PopulateListOfPeople()
{
List<Person> p = new List<Person>();
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(new StringReader(@"[{""Name"":""James""},{""Name"":""Jim""}]"), p);
Assert.AreEqual(2, p.Count);
Assert.AreEqual("James", p[0].Name);
Assert.AreEqual("Jim", p[1].Name);
}
[Test]
public void PopulateDictionary()
{
Dictionary<string, string> p = new Dictionary<string, string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(new StringReader(@"{""Name"":""James""}"), p);
Assert.AreEqual(1, p.Count);
Assert.AreEqual("James", p["Name"]);
}
[Test]
public void PopulateWithBadJson()
{
ExceptionAssert.Throws<JsonSerializationException>("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.",
() =>
{
JsonConvert.PopulateObject("1", new Person());
});
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class PopulateTests : TestFixtureBase
{
[Test]
public void PopulatePerson()
{
Person p = new Person();
JsonConvert.PopulateObject(@"{""Name"":""James""}", p);
Assert.AreEqual("James", p.Name);
}
[Test]
public void PopulateStore()
{
Store s = new Store();
s.Color = StoreColor.Red;
s.product = new List<Product>
{
new Product
{
ExpiryDate = new DateTime(2000, 12, 3, 0, 0, 0, DateTimeKind.Utc),
Name = "ProductName!",
Price = 9.9m
}
};
s.Width = 99.99d;
s.Mottos = new List<string> { "Can do!", "We deliver!" };
string json = @"{
""Color"": 2,
""Establised"": ""\/Date(1264122061000+0000)\/"",
""Width"": 99.99,
""Employees"": 999,
""RoomsPerFloor"": [
1,
2,
3,
4,
5,
6,
7,
8,
9
],
""Open"": false,
""Symbol"": ""@"",
""Mottos"": [
""Fail whale""
],
""Cost"": 100980.1,
""Escape"": ""\r\n\t\f\b?{\\r\\n\""'"",
""product"": [
{
""Name"": ""ProductName!"",
""ExpiryDate"": ""\/Date(975801600000)\/"",
""Price"": 9.9,
""Sizes"": null
}
]
}";
JsonConvert.PopulateObject(json, s, new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
});
Assert.AreEqual(1, s.Mottos.Count);
Assert.AreEqual("Fail whale", s.Mottos[0]);
Assert.AreEqual(1, s.product.Count);
//Assert.AreEqual("James", p.Name);
}
[Test]
public void PopulateListOfPeople()
{
List<Person> p = new List<Person>();
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(new StringReader(@"[{""Name"":""James""},{""Name"":""Jim""}]"), p);
Assert.AreEqual(2, p.Count);
Assert.AreEqual("James", p[0].Name);
Assert.AreEqual("Jim", p[1].Name);
}
[Test]
public void PopulateDictionary()
{
Dictionary<string, string> p = new Dictionary<string, string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(new StringReader(@"{""Name"":""James""}"), p);
Assert.AreEqual(1, p.Count);
Assert.AreEqual("James", p["Name"]);
}
[Test]
public void PopulateWithBadJson()
{
ExceptionAssert.Throws<JsonSerializationException>("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.",
() =>
{
JsonConvert.PopulateObject("1", new Person());
});
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,351 +1,351 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using System.IO;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class SerializationErrorHandlingTests : TestFixtureBase
{
[Test]
public void ErrorDeserializingListHandled()
{
string json = @"[
{
""Name"": ""Jim"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
},
{
""Name"": ""Jim"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
}
]";
VersionKeyedCollection c = JsonConvert.DeserializeObject<VersionKeyedCollection>(json);
Assert.AreEqual(1, c.Count);
Assert.AreEqual(1, c.Messages.Count);
Assert.AreEqual("[1] - Error message for member 1 = An item with the same key has already been added.", c.Messages[0]);
}
[Test]
public void DeserializingErrorInChildObject()
{
ListErrorObjectCollection c = JsonConvert.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);
}
[Test]
public void SerializingErrorInChildObject()
{
ListErrorObjectCollection c = new ListErrorObjectCollection
{
new ListErrorObject
{
Member = "Value1",
ThrowError = "Handle this!",
Member2 = "Member1"
},
new ListErrorObject
{
Member = "Value2",
Member2 = "Member2"
},
new ListErrorObject
{
Member = "Value3",
ThrowError = "Handle that!",
Member2 = "Member3"
}
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"[
{
""Member"": ""Value1"",
""ThrowError"": ""Handle this!"",
""Member2"": ""Member1""
},
{
""Member"": ""Value2""
},
{
""Member"": ""Value3"",
""ThrowError"": ""Handle that!"",
""Member2"": ""Member3""
}
]", json);
}
[Test]
public void DeserializingErrorInDateTimeCollection()
{
DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(@"[
""2009-09-09T00:00:00Z"",
""kjhkjhkjhkjh"",
[
1
],
""1977-02-20T00:00:00Z"",
null,
""2000-12-01T00:00:00Z""
]", new IsoDateTimeConverter());
Assert.AreEqual(3, c.Count);
Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
}
[Test]
public void DeserializingErrorHandlingUsingEvent()
{
List<string> errors = new List<string>();
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(
@"[
""2009-09-09T00:00:00Z"",
""I am not a date and will error!"",
[
1
],
""1977-02-20T00:00:00Z"",
null,
""2000-12-01T00:00:00Z""
]",
new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
Converters = {new IsoDateTimeConverter()}
});
// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.
Assert.AreEqual(3, c.Count);
Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
Assert.AreEqual(3, errors.Count);
#if !(NET20 || NET35 || WINDOWS_PHONE)
Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.", errors[0]);
#else
Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]);
#endif
Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray.", errors[1]);
Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime.", errors[2]);
}
[Test]
public void DeserializingErrorInDateTimeCollectionWithAttributeWithEventNotCalled()
{
bool eventErrorHandlerCalled = false;
DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(
@"[
""2009-09-09T00:00:00Z"",
""kjhkjhkjhkjh"",
[
1
],
""1977-02-20T00:00:00Z"",
null,
""2000-12-01T00:00:00Z""
]",
new JsonSerializerSettings
{
Error = (s, a) => eventErrorHandlerCalled = true,
Converters =
{
new IsoDateTimeConverter()
}
});
Assert.AreEqual(3, c.Count);
Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
Assert.AreEqual(false, eventErrorHandlerCalled);
}
[Test]
public void SerializePerson()
{
PersonError person = new PersonError
{
Name = "George Michael Bluth",
Age = 16,
Roles = null,
Title = "Mister Manager"
};
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(json);
//{
// "Name": "George Michael Bluth",
// "Age": 16,
// "Title": "Mister Manager"
//}
Assert.AreEqual(@"{
""Name"": ""George Michael Bluth"",
""Age"": 16,
""Title"": ""Mister Manager""
}", json);
}
[Test]
public void DeserializeNestedUnhandled()
{
List<string> errors = new List<string>();
string json = @"[[""kjhkjhkjhkjh""]]";
Exception e = null;
try
{
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
// only log an error once
if (args.CurrentObject == args.ErrorContext.OriginalObject)
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
};
serializer.Deserialize(new StringReader(json), typeof(List<List<DateTime>>));
}
catch (Exception ex)
{
e = ex;
}
Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", e.Message);
Assert.AreEqual(1, errors.Count);
Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", errors[0]);
}
[Test]
public void MultipleRequiredPropertyErrors()
{
string json = "{}";
List<string> errors = new List<string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
};
serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof (MyTypeWithRequiredMembers));
Assert.AreEqual(2, errors.Count);
Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Line 1, position 2.", errors[0]);
Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Line 1, position 2.", errors[1]);
}
[Test]
public void HandlingArrayErrors()
{
string json = "[\"a\",\"b\",\"45\",34]";
List<string> errors = new List<string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
};
serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof(int[]));
Assert.AreEqual(2, errors.Count);
Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Line 1, position 4.", errors[0]);
Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Line 1, position 8.", errors[1]);
}
}
[JsonObject]
public class MyTypeWithRequiredMembers
{
[JsonProperty(Required = Required.AllowNull)]
public string Required1;
[JsonProperty(Required = Required.AllowNull)]
public string Required2;
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using System.IO;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class SerializationErrorHandlingTests : TestFixtureBase
{
[Test]
public void ErrorDeserializingListHandled()
{
string json = @"[
{
""Name"": ""Jim"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
},
{
""Name"": ""Jim"",
""BirthDate"": ""\/Date(978048000000)\/"",
""LastModified"": ""\/Date(978048000000)\/""
}
]";
VersionKeyedCollection c = JsonConvert.DeserializeObject<VersionKeyedCollection>(json);
Assert.AreEqual(1, c.Count);
Assert.AreEqual(1, c.Messages.Count);
Assert.AreEqual("[1] - Error message for member 1 = An item with the same key has already been added.", c.Messages[0]);
}
[Test]
public void DeserializingErrorInChildObject()
{
ListErrorObjectCollection c = JsonConvert.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);
}
[Test]
public void SerializingErrorInChildObject()
{
ListErrorObjectCollection c = new ListErrorObjectCollection
{
new ListErrorObject
{
Member = "Value1",
ThrowError = "Handle this!",
Member2 = "Member1"
},
new ListErrorObject
{
Member = "Value2",
Member2 = "Member2"
},
new ListErrorObject
{
Member = "Value3",
ThrowError = "Handle that!",
Member2 = "Member3"
}
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"[
{
""Member"": ""Value1"",
""ThrowError"": ""Handle this!"",
""Member2"": ""Member1""
},
{
""Member"": ""Value2""
},
{
""Member"": ""Value3"",
""ThrowError"": ""Handle that!"",
""Member2"": ""Member3""
}
]", json);
}
[Test]
public void DeserializingErrorInDateTimeCollection()
{
DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(@"[
""2009-09-09T00:00:00Z"",
""kjhkjhkjhkjh"",
[
1
],
""1977-02-20T00:00:00Z"",
null,
""2000-12-01T00:00:00Z""
]", new IsoDateTimeConverter());
Assert.AreEqual(3, c.Count);
Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
}
[Test]
public void DeserializingErrorHandlingUsingEvent()
{
List<string> errors = new List<string>();
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(
@"[
""2009-09-09T00:00:00Z"",
""I am not a date and will error!"",
[
1
],
""1977-02-20T00:00:00Z"",
null,
""2000-12-01T00:00:00Z""
]",
new JsonSerializerSettings
{
Error = delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
Converters = {new IsoDateTimeConverter()}
});
// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.
Assert.AreEqual(3, c.Count);
Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
Assert.AreEqual(3, errors.Count);
#if !(NET20 || NET35 || WINDOWS_PHONE)
Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.", errors[0]);
#else
Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]);
#endif
Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray.", errors[1]);
Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime.", errors[2]);
}
[Test]
public void DeserializingErrorInDateTimeCollectionWithAttributeWithEventNotCalled()
{
bool eventErrorHandlerCalled = false;
DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(
@"[
""2009-09-09T00:00:00Z"",
""kjhkjhkjhkjh"",
[
1
],
""1977-02-20T00:00:00Z"",
null,
""2000-12-01T00:00:00Z""
]",
new JsonSerializerSettings
{
Error = (s, a) => eventErrorHandlerCalled = true,
Converters =
{
new IsoDateTimeConverter()
}
});
Assert.AreEqual(3, c.Count);
Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
Assert.AreEqual(false, eventErrorHandlerCalled);
}
[Test]
public void SerializePerson()
{
PersonError person = new PersonError
{
Name = "George Michael Bluth",
Age = 16,
Roles = null,
Title = "Mister Manager"
};
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
Console.WriteLine(json);
//{
// "Name": "George Michael Bluth",
// "Age": 16,
// "Title": "Mister Manager"
//}
Assert.AreEqual(@"{
""Name"": ""George Michael Bluth"",
""Age"": 16,
""Title"": ""Mister Manager""
}", json);
}
[Test]
public void DeserializeNestedUnhandled()
{
List<string> errors = new List<string>();
string json = @"[[""kjhkjhkjhkjh""]]";
Exception e = null;
try
{
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
// only log an error once
if (args.CurrentObject == args.ErrorContext.OriginalObject)
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
};
serializer.Deserialize(new StringReader(json), typeof(List<List<DateTime>>));
}
catch (Exception ex)
{
e = ex;
}
Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", e.Message);
Assert.AreEqual(1, errors.Count);
Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", errors[0]);
}
[Test]
public void MultipleRequiredPropertyErrors()
{
string json = "{}";
List<string> errors = new List<string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
};
serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof (MyTypeWithRequiredMembers));
Assert.AreEqual(2, errors.Count);
Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Line 1, position 2.", errors[0]);
Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Line 1, position 2.", errors[1]);
}
[Test]
public void HandlingArrayErrors()
{
string json = "[\"a\",\"b\",\"45\",34]";
List<string> errors = new List<string>();
JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
{
errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
};
serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof(int[]));
Assert.AreEqual(2, errors.Count);
Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Line 1, position 4.", errors[0]);
Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Line 1, position 8.", errors[1]);
}
}
[JsonObject]
public class MyTypeWithRequiredMembers
{
[JsonProperty(Required = Required.AllowNull)]
public string Required1;
[JsonProperty(Required = Required.AllowNull)]
public string Required2;
}
}
@@ -1,340 +1,340 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class SerializationEventAttributeTests : TestFixtureBase
{
[Test]
public void ObjectEvents()
{
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.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);
JObject o = JObject.Parse(@"{
""Member1"": 11,
""Member2"": ""This value went into the data file during serialization."",
""Member4"": null
}");
o["Member6"] = "Dummy text for error";
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(o.ToString());
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("Error message for member Member6 = Error setting value to 'Member6' on 'Newtonsoft.Json.Tests.TestObjects.SerializationEventTestObject'.", obj.Member5);
}
[Test]
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.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 = JsonConvert.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);
}
[Test]
public void ListEvents()
{
SerializationEventTestList obj = new SerializationEventTestList
{
1.1m,
2.222222222m,
int.MaxValue,
Convert.ToDecimal(Math.PI)
};
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"[
-1.0,
1.1,
2.222222222,
2147483647.0,
3.14159265358979
]", 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 = JsonConvert.DeserializeObject<SerializationEventTestList>(json);
Assert.AreEqual(11, obj.Member1);
Assert.AreEqual("Hello World!", obj.Member2);
Assert.AreEqual("This value was set during deserialization", obj.Member3);
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
}
[Test]
public void DictionaryEvents()
{
SerializationEventTestDictionary obj = new SerializationEventTestDictionary
{
{ 1.1m, "first" },
{ 2.222222222m, "second" },
{ int.MaxValue, "third" },
{ Convert.ToDecimal(Math.PI), "fourth" }
};
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"{
""1.1"": ""first"",
""2.222222222"": ""second"",
""2147483647"": ""third"",
""3.14159265358979"": ""fourth"",
""79228162514264337593543950335"": ""Inserted on serializing""
}", 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 = JsonConvert.DeserializeObject<SerializationEventTestDictionary>(json);
Assert.AreEqual(11, obj.Member1);
Assert.AreEqual("Hello World!", obj.Member2);
Assert.AreEqual("This value was set during deserialization", obj.Member3);
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
}
[Test]
public void ObjectEventsDocumentationExample()
{
SerializationEventTestObject obj = new SerializationEventTestObject();
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// Hello World!
Console.WriteLine(obj.Member3);
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
Console.WriteLine(obj.Member5);
// null
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
// {
// "Member1": 11,
// "Member2": "This value went into the data file during serialization.",
// "Member4": null
// }
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// This value was reset after serialization.
Console.WriteLine(obj.Member3);
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
Console.WriteLine(obj.Member5);
// Error message for member Member6 = Exception has been thrown by the target of an invocation.
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// This value went into the data file during serialization.
Console.WriteLine(obj.Member3);
// This value was set during deserialization
Console.WriteLine(obj.Member4);
// This value was set after deserialization.
}
public class SerializationEventBaseTestObject
{
public string TestMember { get; set; }
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
TestMember = "Set!";
}
}
public class SerializationEventContextSubClassTestObject : SerializationEventBaseTestObject
{
}
[Test]
public void SerializationEventContextTestObjectSubClassTest()
{
SerializationEventContextSubClassTestObject obj = new SerializationEventContextSubClassTestObject();
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"{
""TestMember"": ""Set!""
}", json);
}
#if !SILVERLIGHT && !NETFX_CORE
public class SerializationEventContextTestObject
{
public string TestMember { get; set; }
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
TestMember = context.State + " " + context.Context;
}
}
[Test]
public void SerializationEventContextTest()
{
SerializationEventContextTestObject value = new SerializationEventContextTestObject();
string json = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings
{
Context =
new StreamingContext(
StreamingContextStates.Remoting,
"ContextValue")
});
Assert.AreEqual(@"{
""TestMember"": ""Remoting ContextValue""
}", json);
}
#endif
public void WhenSerializationErrorDetectedBySerializer_ThenCallbackIsCalled()
{
// Verify contract is properly finding our callback
var resolver = new DefaultContractResolver().ResolveContract(typeof(FooEvent));
Debug.Assert(resolver.OnError != null);
Debug.Assert(resolver.OnError == typeof(FooEvent).GetMethod("OnError", BindingFlags.Instance | BindingFlags.NonPublic));
var serializer = JsonSerializer.Create(new JsonSerializerSettings
{
// If I don't specify Error here, the callback isn't called
// either, but no exception is thrown.
MissingMemberHandling = MissingMemberHandling.Error,
});
// This throws with missing member exception, rather than calling my callback.
var foo = serializer.Deserialize<FooEvent>(new JsonTextReader(new StringReader("{ Id: 25 }")));
// When fixed, this would pass.
Debug.Assert(foo.Identifier == 25);
}
public class FooEvent
{
public int Identifier { get; set; }
[OnError]
private void OnError(StreamingContext context, ErrorContext error)
{
this.Identifier = 25;
// Here we could for example manually copy the
// persisted "Id" value into the renamed "Identifier"
// property, etc.
error.Handled = true;
// We never get here :(
Console.WriteLine("Error has been fixed");
}
}
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class SerializationEventAttributeTests : TestFixtureBase
{
[Test]
public void ObjectEvents()
{
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.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);
JObject o = JObject.Parse(@"{
""Member1"": 11,
""Member2"": ""This value went into the data file during serialization."",
""Member4"": null
}");
o["Member6"] = "Dummy text for error";
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(o.ToString());
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("Error message for member Member6 = Error setting value to 'Member6' on 'Newtonsoft.Json.Tests.TestObjects.SerializationEventTestObject'.", obj.Member5);
}
[Test]
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.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 = JsonConvert.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);
}
[Test]
public void ListEvents()
{
SerializationEventTestList obj = new SerializationEventTestList
{
1.1m,
2.222222222m,
int.MaxValue,
Convert.ToDecimal(Math.PI)
};
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"[
-1.0,
1.1,
2.222222222,
2147483647.0,
3.14159265358979
]", 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 = JsonConvert.DeserializeObject<SerializationEventTestList>(json);
Assert.AreEqual(11, obj.Member1);
Assert.AreEqual("Hello World!", obj.Member2);
Assert.AreEqual("This value was set during deserialization", obj.Member3);
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
}
[Test]
public void DictionaryEvents()
{
SerializationEventTestDictionary obj = new SerializationEventTestDictionary
{
{ 1.1m, "first" },
{ 2.222222222m, "second" },
{ int.MaxValue, "third" },
{ Convert.ToDecimal(Math.PI), "fourth" }
};
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 = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"{
""1.1"": ""first"",
""2.222222222"": ""second"",
""2147483647"": ""third"",
""3.14159265358979"": ""fourth"",
""79228162514264337593543950335"": ""Inserted on serializing""
}", 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 = JsonConvert.DeserializeObject<SerializationEventTestDictionary>(json);
Assert.AreEqual(11, obj.Member1);
Assert.AreEqual("Hello World!", obj.Member2);
Assert.AreEqual("This value was set during deserialization", obj.Member3);
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
}
[Test]
public void ObjectEventsDocumentationExample()
{
SerializationEventTestObject obj = new SerializationEventTestObject();
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// Hello World!
Console.WriteLine(obj.Member3);
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
Console.WriteLine(obj.Member5);
// null
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
// {
// "Member1": 11,
// "Member2": "This value went into the data file during serialization.",
// "Member4": null
// }
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// This value was reset after serialization.
Console.WriteLine(obj.Member3);
// This is a nonserialized value
Console.WriteLine(obj.Member4);
// null
Console.WriteLine(obj.Member5);
// Error message for member Member6 = Exception has been thrown by the target of an invocation.
obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
Console.WriteLine(obj.Member1);
// 11
Console.WriteLine(obj.Member2);
// This value went into the data file during serialization.
Console.WriteLine(obj.Member3);
// This value was set during deserialization
Console.WriteLine(obj.Member4);
// This value was set after deserialization.
}
public class SerializationEventBaseTestObject
{
public string TestMember { get; set; }
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
TestMember = "Set!";
}
}
public class SerializationEventContextSubClassTestObject : SerializationEventBaseTestObject
{
}
[Test]
public void SerializationEventContextTestObjectSubClassTest()
{
SerializationEventContextSubClassTestObject obj = new SerializationEventContextSubClassTestObject();
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Assert.AreEqual(@"{
""TestMember"": ""Set!""
}", json);
}
#if !SILVERLIGHT && !NETFX_CORE
public class SerializationEventContextTestObject
{
public string TestMember { get; set; }
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
TestMember = context.State + " " + context.Context;
}
}
[Test]
public void SerializationEventContextTest()
{
SerializationEventContextTestObject value = new SerializationEventContextTestObject();
string json = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings
{
Context =
new StreamingContext(
StreamingContextStates.Remoting,
"ContextValue")
});
Assert.AreEqual(@"{
""TestMember"": ""Remoting ContextValue""
}", json);
}
#endif
public void WhenSerializationErrorDetectedBySerializer_ThenCallbackIsCalled()
{
// Verify contract is properly finding our callback
var resolver = new DefaultContractResolver().ResolveContract(typeof(FooEvent));
Debug.Assert(resolver.OnError != null);
Debug.Assert(resolver.OnError == typeof(FooEvent).GetMethod("OnError", BindingFlags.Instance | BindingFlags.NonPublic));
var serializer = JsonSerializer.Create(new JsonSerializerSettings
{
// If I don't specify Error here, the callback isn't called
// either, but no exception is thrown.
MissingMemberHandling = MissingMemberHandling.Error,
});
// This throws with missing member exception, rather than calling my callback.
var foo = serializer.Deserialize<FooEvent>(new JsonTextReader(new StringReader("{ Id: 25 }")));
// When fixed, this would pass.
Debug.Assert(foo.Identifier == 25);
}
public class FooEvent
{
public int Identifier { get; set; }
[OnError]
private void OnError(StreamingContext context, ErrorContext error)
{
this.Identifier = 25;
// Here we could for example manually copy the
// persisted "Id" value into the renamed "Identifier"
// property, etc.
error.Handled = true;
// We never get here :(
Console.WriteLine("Error has been fixed");
}
}
}
}
#endif
File diff suppressed because it is too large Load Diff