-Added ObjectCreationHandling to JsonPropertyAttribute

-Added IValueProvider, ReflectionValueProvider, DynamicValueProvider
-Added Dynamic.snk
-Added Required enum with options Default, AllowNull and Always
-Added serialization event support to Silverlight version
-Added Converter to JsonProperty for JsonConverter
-Changed IsRequired to Required enum
-Changed schema generator to allow for Required enum options
-Changed Silverlight project version to Silverlight 3
-Improved error message when JSON array encountered for object and vice-versa when deserializing
-Improved error message for converting types when deserializing
-Improved error message from getting and setting properties when serializing and deserializing
-Fixed empty string being converted to null when deserializing
-Removed dependency on Entity Framework and LINQ to SQL assemblies
This commit is contained in:
JamesNK
2009-11-02 08:21:02 +00:00
parent b4b3905714
commit 2a63ea24e3
51 changed files with 1466 additions and 260 deletions
@@ -12,6 +12,11 @@
<AssemblyName>Newtonsoft.Json.Tests.Silverlight</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<SilverlightApplication>false</SilverlightApplication>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -195,7 +200,7 @@
<Name>Newtonsoft.Json.Silverlight</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight\v2.0\Microsoft.Silverlight.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Silverlight\v3.0\Microsoft.Silverlight.CSharp.targets" Condition="" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
@@ -113,6 +113,12 @@
<Compile Include="Linq\ComponentModel\JTypeDescriptorTests.cs" />
<Compile Include="Linq\JPathTests.cs" />
<Compile Include="Serialization\ConstructorHandlingTests.cs" />
<Compile Include="Serialization\ContractResolverTests.cs" />
<Compile Include="Serialization\DefaultValueHandlingTests.cs" />
<Compile Include="Serialization\NullValueHandlingTests.cs" />
<Compile Include="TestObjects\Car.cs" />
<Compile Include="TestObjects\Computer.cs" />
<Compile Include="TestObjects\Movie.cs" />
<Compile Include="TestObjects\PersonError.cs" />
<Compile Include="TestObjects\PrivateConstructorTestClass.cs" />
<Compile Include="TestObjects\PrivateConstructorWithPublicParametizedConstructorTestClass.cs" />
@@ -21,6 +21,7 @@ namespace Newtonsoft.Json.Tests
public class PerformanceTests : TestFixtureBase
{
private int Iterations = 100;
//private int Iterations = 5000;
public enum SerializeMethod
{
@@ -59,7 +59,7 @@ namespace Newtonsoft.Json.Tests.Schema
}
}", json);
}
#if !PocketPC
[Test]
public void Generate_DefaultValueAttributeTestClass()
@@ -179,7 +179,7 @@ namespace Newtonsoft.Json.Tests.Schema
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
@@ -264,7 +264,7 @@ namespace Newtonsoft.Json.Tests.Schema
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
@@ -287,7 +287,7 @@ namespace Newtonsoft.Json.Tests.Schema
{
IList<JsonProperty> properties = base.CreateProperties(contract);
JsonPropertyCollection c = new JsonPropertyCollection();
JsonPropertyCollection c = new JsonPropertyCollection(contract);
CollectionUtils.AddRange(c, (IEnumerable)properties.Where(m => m.PropertyName != "Root"));
return c;
@@ -116,7 +116,9 @@ namespace Newtonsoft.Json.Tests.Serialization
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));
Assert.AreEqual(-2, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
// readonly
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
[Test]
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Tests.Serialization
{
public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
{
_startingWithChar = startingWithChar;
}
protected override IList<JsonProperty> CreateProperties(JsonObjectContract contract)
{
IList<JsonProperty> properties = base.CreateProperties(contract);
// 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 ContractResolverTests : TestFixtureBase
{
[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);
}
}
}
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
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 DefaultValueAttributeTest()
{
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);
}
}
}
@@ -45,6 +45,7 @@ using System.Runtime.Serialization.Json;
using Newtonsoft.Json.Tests.TestObjects;
using System.Runtime.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
@@ -60,6 +61,7 @@ namespace Newtonsoft.Json.Tests.Serialization
Store deserializedStore = (Store)JsonConvert.DeserializeObject(jsonText, typeof(Store));
Assert.AreEqual(store.Establised, deserializedStore.Establised);
Assert.AreEqual(store.product.Count, deserializedStore.product.Count);
Console.WriteLine(jsonText);
}
@@ -509,31 +511,6 @@ keyword such as type of business.""
CollectionAssert.AreEqual(collection, collectionNew);
}
[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"":""\/Date(1264122061000+0000)\/"",""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(949532490000)\/"",""Price"":0.0},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""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 SerializeObject()
{
@@ -860,49 +837,6 @@ keyword such as type of business.""
Assert.AreEqual(@"{""Id"":0}", json);
}
[Test]
public void DefaultValueAttributeTest()
{
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 SerializeInvoice()
{
Invoice invoice = new Invoice
{
Company = "Acme Ltd.",
Amount = 50.0m,
Paid = false
};
string json = JsonConvert.SerializeObject(invoice);
Console.WriteLine(json);
// {"Company":"Acme Ltd.","Amount":50.0,"Paid":false,"PaidDate":null}
json = JsonConvert.SerializeObject(invoice,
Formatting.None,
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
Console.WriteLine(json);
// {"Company":"Acme Ltd.","Amount":50.0}
}
[Test]
public void DeserializeNullable()
{
@@ -1024,7 +958,7 @@ keyword such as type of business.""
public void RequiredMembersClassWithNullValues()
{
string json = @"{
""FirstName"": null,
""FirstName"": ""I can't be null bro!"",
""MiddleName"": null,
""LastName"": null,
""BirthDate"": ""\/Date(977309755000)\/""
@@ -1032,7 +966,23 @@ keyword such as type of business.""
RequiredMembersClass c = JsonConvert.DeserializeObject<RequiredMembersClass>(json);
Assert.AreEqual(null, c.FirstName);
Assert.AreEqual("I can't be null bro!", c.FirstName);
Assert.AreEqual(null, c.MiddleName);
Assert.AreEqual(null, c.LastName);
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null.")]
public void RequiredMembersClassNullRequiredValueProperty()
{
string json = @"{
""FirstName"": null,
""MiddleName"": null,
""LastName"": null,
""BirthDate"": ""\/Date(977309755000)\/""
}";
JsonConvert.DeserializeObject<RequiredMembersClass>(json);
}
[Test]
@@ -1815,20 +1765,151 @@ keyword such as type of business.""
}
[Test]
public void DeserializeNullableListWithNullss()
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array into type 'Newtonsoft.Json.Tests.TestObjects.Person'.")]
public void CannotDeserializeArrayIntoObject()
{
//JavaScriptSerializer s = new JavaScriptSerializer();
//s.Deserialize<List<decimal?>>("[ 3.3, null, 1.1 ] ");
string json = @"[]";
//DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(List<decimal?>));
//s.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes("[ 3.3, null, 1.1 ] ")));
JsonConvert.DeserializeObject<Person>(json);
}
List<decimal?> l = JsonConvert.DeserializeObject<List<decimal?>>("[ 3.3, null, 1.1 ] ");
Assert.AreEqual(3, l.Count);
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.")]
public void CannotDeserializeObjectIntoArray()
{
string json = @"{}";
Assert.AreEqual(3.3m, l[0]);
Assert.AreEqual(null, l[1]);
Assert.AreEqual(1.1m, l[2]);
JsonConvert.DeserializeObject<List<Person>>(json);
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'.")]
public void CannotPopulateArrayIntoObject()
{
string json = @"[]";
JsonConvert.PopulateObject(json, new Person());
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.")]
public void CannotPopulateObjectIntoArray()
{
string json = @"{}";
JsonConvert.PopulateObject(json, new List<Person>());
}
[Test]
public void DeserializeEmptyString()
{
string json = @"{""Name"":""""}";
Person p = JsonConvert.DeserializeObject<Person>(json);
Assert.AreEqual("", p.Name);
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.")]
public void SerializePropertyGetError()
{
JsonConvert.SerializeObject(new MemoryStream());
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.")]
public void DeserializePropertySetError()
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}");
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value """" to type 'System.Int32'.")]
public void DeserializeEnsureTypeEmptyStringToIntError()
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}");
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'.")]
public void DeserializeEnsureTypeNullToIntError()
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}");
}
[Test]
public void SerializeGenericListOfStrings()
{
List<String> strings = new List<String>();
strings.Add("str_1");
strings.Add("str_2");
strings.Add("str_3");
string json = JsonConvert.SerializeObject(strings);
Assert.AreEqual(@"[""str_1"",""str_2"",""str_3""]", json);
}
public class ConstructorReadonlyFields
{
public readonly string A;
public readonly int B;
public ConstructorReadonlyFields(string a, int b)
{
A = a;
B = b;
}
}
[Test]
public void ConstructorReadonlyFieldsTest()
{
ConstructorReadonlyFields c1 = new ConstructorReadonlyFields("String!", int.MaxValue);
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
Assert.AreEqual(@"{
""A"": ""String!"",
""B"": 2147483647
}", json);
ConstructorReadonlyFields c2 = JsonConvert.DeserializeObject<ConstructorReadonlyFields>(json);
Assert.AreEqual("String!", c2.A);
Assert.AreEqual(int.MaxValue, c2.B);
}
public struct StructTest
{
public string StringProperty { get; set; }
public string StringField;
public int IntProperty { get; set; }
public int IntField;
}
[Test]
public void SerializeStruct()
{
StructTest structTest = new StructTest
{
StringProperty = "StringProperty!",
StringField = "StringField",
IntProperty = 5,
IntField = 10
};
string json = JsonConvert.SerializeObject(structTest, Formatting.Indented);
Console.WriteLine(json);
Assert.AreEqual(@"{
""StringField"": ""StringField"",
""IntField"": 10,
""StringProperty"": ""StringProperty!"",
""IntProperty"": 5
}", json);
StructTest deserialized = JsonConvert.DeserializeObject<StructTest>(json);
Assert.AreEqual(structTest.StringProperty, deserialized.StringProperty);
Assert.AreEqual(structTest.StringField, deserialized.StringField);
Assert.AreEqual(structTest.IntProperty, deserialized.IntProperty);
Assert.AreEqual(structTest.IntField, deserialized.IntField);
}
}
}
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
public class NullValueHandlingTests : TestFixtureBase
{
[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"":""\/Date(1264122061000+0000)\/"",""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(949532490000)\/"",""Price"":0.0},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""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);
}
}
}
@@ -327,12 +327,13 @@ namespace Newtonsoft.Json.Tests.Serialization
serializer.Deserialize(new StringReader(json), typeof(List<List<DateTime>>));
}
catch
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("Could not cast or convert from System.String to System.DateTime.", errors[0]);
Assert.AreEqual(@"Error converting value ""kjhkjhkjhkjh"" to type 'System.DateTime'.", errors[0]);
}
}
}
@@ -23,7 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !SILVERLIGHT && !NET20
#if !PocketPC && !NET20
using System;
using System.IO;
using System.Linq;
@@ -61,7 +61,7 @@ namespace Newtonsoft.Json.Tests.Serialization
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 = Exception has been thrown by the target of an invocation.", obj.Member5);
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,
@@ -76,7 +76,7 @@ namespace Newtonsoft.Json.Tests.Serialization
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 = Exception has been thrown by the target of an invocation.", obj.Member5);
Assert.AreEqual("Error message for member Member6 = Error setting value to 'Member6' on 'Newtonsoft.Json.Tests.TestObjects.SerializationEventTestObject'.", obj.Member5);
}
[Test]
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
}
@@ -32,7 +32,7 @@ namespace Newtonsoft.Json.Tests.TestObjects
{
public class CircularReferenceClass
{
[JsonProperty(IsRequired = true)]
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
public CircularReferenceClass Child { get; set; }
}
@@ -33,7 +33,7 @@ namespace Newtonsoft.Json.Tests.TestObjects
[JsonObject(Id = "MyExplicitId")]
public class CircularReferenceWithIdClass
{
[JsonProperty(IsRequired = true)]
[JsonProperty(Required = Required.AllowNull)]
public string Name { get; set; }
public CircularReferenceWithIdClass Child { get; set; }
}
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
}
@@ -32,9 +32,16 @@ namespace Newtonsoft.Json.Tests.TestObjects
{
public string Company { get; set; }
public decimal Amount { get; set; }
[DefaultValue(false)]
// false is default value of bool
public bool Paid { get; set; }
[DefaultValue(null)]
// null is default value of nullable
public DateTime? PaidDate { get; set; }
// customize default values
[DefaultValue(30)]
public int FollowUpDays { get; set; }
[DefaultValue("")]
public string FollowUpEmailAddress { get; set; }
}
}
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class Movie
{
public string Name { get; set; }
public string Description { get; set; }
public string Classification { get; set; }
public string Studio { get; set; }
public DateTime? ReleaseDate { get; set; }
public List<string> ReleaseCountries { get; set; }
}
}
@@ -32,16 +32,16 @@ namespace Newtonsoft.Json.Tests.TestObjects
{
public class RequiredMembersClass
{
[JsonProperty(IsRequired = true)]
[JsonProperty(Required = Required.Always)]
public string FirstName { get; set; }
[JsonProperty]
public string MiddleName { get; set; }
[JsonProperty(IsRequired = true)]
[JsonProperty(Required = Required.AllowNull)]
public string LastName { get; set; }
[JsonProperty(IsRequired = true)]
[JsonProperty(Required = Required.Default)]
public DateTime BirthDate { get; set; }
}
}
@@ -23,7 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !SILVERLIGHT
#if !PocketPC
using System.Collections.Generic;
using System.Runtime.Serialization;
@@ -23,7 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !SILVERLIGHT
#if !PocketPC
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json.Tests.Serialization;
@@ -23,7 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !SILVERLIGHT && !NET20
#if !PocketPC && !NET20
using System;
using System.Linq;
using System.Runtime.Serialization;
@@ -23,7 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PocketPC && !SILVERLIGHT
#if !PocketPC
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
@@ -37,9 +37,11 @@ namespace Newtonsoft.Json.Tests.TestObjects
public int[] RoomsPerFloor = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public bool Open = false;
public char Symbol = '@';
[JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace)]
public List<string> Mottos = new List<string>();
public decimal Cost = 100980.1M;
public string Escape = "\r\n\t\f\b?{\\r\\n\"\'";
[JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Replace)]
public List<Product> product = new List<Product>();
public Store()