-More documentation (I know!)

-Fixed decimals to always be written with a decimal place
-Replaced IMappingResolver with IContractResolver
-Renamed JsonMemberMapping to JsonProperty
-Added JsonContract, JsonObjectContract, JsonArrayContract, JsonDictionaryContract
-Added support for OnSerializing, OnSerialized, OnDeserializing, OnDeserialized callback methods
-Major refactoring of serialization internals
This commit is contained in:
JamesNK
2009-07-05 02:55:58 +00:00
parent 6b19c9cf72
commit a4022ec5d3
51 changed files with 3317 additions and 1826 deletions
@@ -1,4 +1,4 @@
#region License
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
@@ -36,7 +36,7 @@ using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
public class CamelCaseMappingResolverTests : TestFixtureBase
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
@@ -48,7 +48,7 @@ namespace Newtonsoft.Json.Tests.Serialization
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver()
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
@@ -59,7 +59,7 @@ namespace Newtonsoft.Json.Tests.Serialization
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver()
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
@@ -74,7 +74,7 @@ namespace Newtonsoft.Json.Tests.Serialization
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.MappingResolver = new CamelCaseMappingResolver();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
JTokenWriter writer = new JTokenWriter();
@@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Tests.Serialization
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual(@"{
@@ -111,7 +111,7 @@ namespace Newtonsoft.Json.Tests.Serialization
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
MappingResolver = new CamelCaseMappingResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
@@ -134,7 +134,7 @@ namespace Newtonsoft.Json.Tests.Serialization
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { MappingResolver = new CamelCaseMappingResolver() }
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
@@ -0,0 +1,654 @@
#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.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
public class PreserveReferencesHandlingTests : TestFixtureBase
{
[Test]
public void SerializeDictionarysWithPreserveObjectReferences()
{
CircularDictionary circularDictionary = new CircularDictionary();
circularDictionary.Add("other", new CircularDictionary { { "blah", null } });
circularDictionary.Add("self", circularDictionary);
string json = JsonConvert.SerializeObject(circularDictionary, Formatting.Indented,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
Assert.AreEqual(@"{
""$id"": ""1"",
""other"": {
""$id"": ""2"",
""blah"": null
},
""self"": {
""$ref"": ""1""
}
}", json);
}
[Test]
public void DeserializeDictionarysWithPreserveObjectReferences()
{
string json = @"{
""$id"": ""1"",
""other"": {
""$id"": ""2"",
""blah"": null
},
""self"": {
""$ref"": ""1""
}
}";
CircularDictionary circularDictionary = JsonConvert.DeserializeObject<CircularDictionary>(json,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
});
Assert.AreEqual(2, circularDictionary.Count);
Assert.AreEqual(1, circularDictionary["other"].Count);
Assert.AreEqual(circularDictionary, circularDictionary["self"]);
}
public class CircularList : List<CircularList>
{
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Self referencing loop")]
public void SerializeCircularListsError()
{
CircularList circularList = new CircularList();
circularList.Add(null);
circularList.Add(new CircularList { null });
circularList.Add(new CircularList { new CircularList { circularList } });
JsonConvert.SerializeObject(circularList, Formatting.Indented);
}
[Test]
public void SerializeCircularListsIgnore()
{
CircularList circularList = new CircularList();
circularList.Add(null);
circularList.Add(new CircularList { null });
circularList.Add(new CircularList { new CircularList { circularList } });
string json = JsonConvert.SerializeObject(circularList,
Formatting.Indented,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Assert.AreEqual(@"[
null,
[
null
],
[
[]
]
]", json);
}
[Test]
public void SerializeListsWithPreserveObjectReferences()
{
CircularList circularList = new CircularList();
circularList.Add(null);
circularList.Add(new CircularList { null });
circularList.Add(new CircularList { new CircularList { circularList } });
string json = JsonConvert.SerializeObject(circularList, Formatting.Indented,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
WriteEscapedJson(json);
Assert.AreEqual(@"{
""$id"": ""1"",
""$values"": [
null,
{
""$id"": ""2"",
""$values"": [
null
]
},
{
""$id"": ""3"",
""$values"": [
{
""$id"": ""4"",
""$values"": [
{
""$ref"": ""1""
}
]
}
]
}
]
}", json);
}
[Test]
public void DeserializeListsWithPreserveObjectReferences()
{
string json = @"{
""$id"": ""1"",
""$values"": [
null,
{
""$id"": ""2"",
""$values"": [
null
]
},
{
""$id"": ""3"",
""$values"": [
{
""$id"": ""4"",
""$values"": [
{
""$ref"": ""1""
}
]
}
]
}
]
}";
CircularList circularList = JsonConvert.DeserializeObject<CircularList>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
Assert.AreEqual(3, circularList.Count);
Assert.AreEqual(null, circularList[0]);
Assert.AreEqual(1, circularList[1].Count);
Assert.AreEqual(1, circularList[2].Count);
Assert.AreEqual(1, circularList[2][0].Count);
Assert.IsTrue(ReferenceEquals(circularList, circularList[2][0][0]));
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]")]
public void DeserializeArraysWithPreserveObjectReferences()
{
string json = @"{
""$id"": ""1"",
""$values"": [
null,
{
""$id"": ""2"",
""$values"": [
null
]
},
{
""$id"": ""3"",
""$values"": [
{
""$id"": ""4"",
""$values"": [
{
""$ref"": ""1""
}
]
}
]
}
]
}";
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
}
public class CircularDictionary : Dictionary<string, CircularDictionary>
{
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Self referencing loop")]
public void SerializeCircularDictionarysError()
{
CircularDictionary circularDictionary = new CircularDictionary();
circularDictionary.Add("other", new CircularDictionary { { "blah", null } });
circularDictionary.Add("self", circularDictionary);
JsonConvert.SerializeObject(circularDictionary, Formatting.Indented);
}
[Test]
public void SerializeCircularDictionarysIgnore()
{
CircularDictionary circularDictionary = new CircularDictionary();
circularDictionary.Add("other", new CircularDictionary { { "blah", null } });
circularDictionary.Add("self", circularDictionary);
string json = JsonConvert.SerializeObject(circularDictionary, Formatting.Indented,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Assert.AreEqual(@"{
""other"": {
""blah"": null
}
}", json);
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unexpected end when deserializing object.")]
public void UnexpectedEnd()
{
string json = @"{
""$id"":";
JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
}
public class CircularReferenceClassConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
CircularReferenceClass circularReferenceClass = (CircularReferenceClass)value;
string reference = serializer.ReferenceResolver.GetReference(circularReferenceClass);
JObject me = new JObject();
me["$id"] = new JValue(reference);
me["$type"] = new JValue(value.GetType().Name);
me["Name"] = new JValue(circularReferenceClass.Name);
JObject o = JObject.FromObject(circularReferenceClass.Child, serializer);
me["Child"] = o;
me.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
{
JObject o = JObject.Load(reader);
string id = (string)o["$id"];
if (id != null)
{
CircularReferenceClass circularReferenceClass = new CircularReferenceClass();
serializer.Populate(o.CreateReader(), circularReferenceClass);
return circularReferenceClass;
}
else
{
string reference = (string)o["$ref"];
return serializer.ReferenceResolver.ResolveReference(reference);
}
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(CircularReferenceClass));
}
}
[Test]
public void SerializeCircularReferencesWithConverter()
{
CircularReferenceClass c1 = new CircularReferenceClass { Name = "c1" };
CircularReferenceClass c2 = new CircularReferenceClass { Name = "c2" };
CircularReferenceClass c3 = new CircularReferenceClass { Name = "c3" };
c1.Child = c2;
c2.Child = c3;
c3.Child = c1;
string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Converters = new List<JsonConverter> { new CircularReferenceClassConverter() }
});
Assert.AreEqual(@"{
""$id"": ""1"",
""$type"": ""CircularReferenceClass"",
""Name"": ""c1"",
""Child"": {
""$id"": ""2"",
""$type"": ""CircularReferenceClass"",
""Name"": ""c2"",
""Child"": {
""$id"": ""3"",
""$type"": ""CircularReferenceClass"",
""Name"": ""c3"",
""Child"": {
""$ref"": ""1""
}
}
}
}", json);
}
[Test]
public void DeserializeCircularReferencesWithConverter()
{
string json = @"{
""$id"": ""1"",
""$type"": ""CircularReferenceClass"",
""Name"": ""c1"",
""Child"": {
""$id"": ""2"",
""$type"": ""CircularReferenceClass"",
""Name"": ""c2"",
""Child"": {
""$id"": ""3"",
""$type"": ""CircularReferenceClass"",
""Name"": ""c3"",
""Child"": {
""$ref"": ""1""
}
}
}
}";
CircularReferenceClass c1 = JsonConvert.DeserializeObject<CircularReferenceClass>(json, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Converters = new List<JsonConverter> { new CircularReferenceClassConverter() }
});
Assert.AreEqual("c1", c1.Name);
Assert.AreEqual("c2", c1.Child.Name);
Assert.AreEqual("c3", c1.Child.Child.Name);
Assert.AreEqual("c1", c1.Child.Child.Child.Name);
}
[Test]
public void SerializeEmployeeReference()
{
EmployeeReference mikeManager = new EmployeeReference
{
Name = "Mike Manager"
};
EmployeeReference joeUser = new EmployeeReference
{
Name = "Joe User",
Manager = mikeManager
};
List<EmployeeReference> employees = new List<EmployeeReference>
{
mikeManager,
joeUser
};
string json = JsonConvert.SerializeObject(employees, Formatting.Indented);
Assert.AreEqual(@"[
{
""$id"": ""1"",
""Name"": ""Mike Manager"",
""Manager"": null
},
{
""$id"": ""2"",
""Name"": ""Joe User"",
""Manager"": {
""$ref"": ""1""
}
}
]", json);
}
[Test]
public void DeserializeEmployeeReference()
{
string json = @"[
{
""$id"": ""1"",
""Name"": ""Mike Manager"",
""Manager"": null
},
{
""$id"": ""2"",
""Name"": ""Joe User"",
""Manager"": {
""$ref"": ""1""
}
}
]";
List<EmployeeReference> employees = JsonConvert.DeserializeObject<List<EmployeeReference>>(json);
Assert.AreEqual(2, employees.Count);
Assert.AreEqual("Mike Manager", employees[0].Name);
Assert.AreEqual("Joe User", employees[1].Name);
Assert.AreEqual(employees[0], employees[1].Manager);
}
[Test]
public void SerializeCircularReference()
{
CircularReferenceClass c1 = new CircularReferenceClass { Name = "c1" };
CircularReferenceClass c2 = new CircularReferenceClass { Name = "c2" };
CircularReferenceClass c3 = new CircularReferenceClass { Name = "c3" };
c1.Child = c2;
c2.Child = c3;
c3.Child = c1;
string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
Assert.AreEqual(@"{
""$id"": ""1"",
""Name"": ""c1"",
""Child"": {
""$id"": ""2"",
""Name"": ""c2"",
""Child"": {
""$id"": ""3"",
""Name"": ""c3"",
""Child"": {
""$ref"": ""1""
}
}
}
}", json);
}
[Test]
public void DeserializeCircularReference()
{
string json = @"{
""$id"": ""1"",
""Name"": ""c1"",
""Child"": {
""$id"": ""2"",
""Name"": ""c2"",
""Child"": {
""$id"": ""3"",
""Name"": ""c3"",
""Child"": {
""$ref"": ""1""
}
}
}
}";
CircularReferenceClass c1 =
JsonConvert.DeserializeObject<CircularReferenceClass>(json, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
Assert.AreEqual("c1", c1.Name);
Assert.AreEqual("c2", c1.Child.Name);
Assert.AreEqual("c3", c1.Child.Child.Name);
Assert.AreEqual("c1", c1.Child.Child.Child.Name);
}
[Test]
public void SerializeReferenceInList()
{
EmployeeReference e1 = new EmployeeReference { Name = "e1" };
EmployeeReference e2 = new EmployeeReference { Name = "e2" };
List<EmployeeReference> employees = new List<EmployeeReference> { e1, e2, e1, e2 };
string json = JsonConvert.SerializeObject(employees, Formatting.Indented);
Assert.AreEqual(@"[
{
""$id"": ""1"",
""Name"": ""e1"",
""Manager"": null
},
{
""$id"": ""2"",
""Name"": ""e2"",
""Manager"": null
},
{
""$ref"": ""1""
},
{
""$ref"": ""2""
}
]", json);
}
[Test]
public void DeserializeReferenceInList()
{
string json = @"[
{
""$id"": ""1"",
""Name"": ""e1"",
""Manager"": null
},
{
""$id"": ""2"",
""Name"": ""e2"",
""Manager"": null
},
{
""$ref"": ""1""
},
{
""$ref"": ""2""
}
]";
List<EmployeeReference> employees = JsonConvert.DeserializeObject<List<EmployeeReference>>(json);
Assert.AreEqual(4, employees.Count);
Assert.AreEqual("e1", employees[0].Name);
Assert.AreEqual("e2", employees[1].Name);
Assert.AreEqual("e1", employees[2].Name);
Assert.AreEqual("e2", employees[3].Name);
Assert.AreEqual(employees[0], employees[2]);
Assert.AreEqual(employees[1], employees[3]);
}
[Test]
public void SerializeReferenceInDictionary()
{
EmployeeReference e1 = new EmployeeReference { Name = "e1" };
EmployeeReference e2 = new EmployeeReference { Name = "e2" };
Dictionary<string, EmployeeReference> employees = new Dictionary<string, EmployeeReference>
{
{"One", e1},
{"Two", e2},
{"Three", e1},
{"Four", e2}
};
string json = JsonConvert.SerializeObject(employees, Formatting.Indented);
Assert.AreEqual(@"{
""One"": {
""$id"": ""1"",
""Name"": ""e1"",
""Manager"": null
},
""Two"": {
""$id"": ""2"",
""Name"": ""e2"",
""Manager"": null
},
""Three"": {
""$ref"": ""1""
},
""Four"": {
""$ref"": ""2""
}
}", json);
}
[Test]
public void DeserializeReferenceInDictionary()
{
string json = @"{
""One"": {
""$id"": ""1"",
""Name"": ""e1"",
""Manager"": null
},
""Two"": {
""$id"": ""2"",
""Name"": ""e2"",
""Manager"": null
},
""Three"": {
""$ref"": ""1""
},
""Four"": {
""$ref"": ""2""
}
}";
Dictionary<string, EmployeeReference> employees = JsonConvert.DeserializeObject<Dictionary<string, EmployeeReference>>(json);
Assert.AreEqual(4, employees.Count);
EmployeeReference e1 = employees["One"];
EmployeeReference e2 = employees["Two"];
Assert.AreEqual("e1", e1.Name);
Assert.AreEqual("e2", e2.Name);
Assert.AreEqual(e1, employees["Three"]);
Assert.AreEqual(e2, employees["Four"]);
}
}
}
@@ -0,0 +1,220 @@
#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 && !SILVERLIGHT
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Tests;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
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);
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<SerializationEventTestObject>(json);
Assert.AreEqual(11, obj.Member1);
Assert.AreEqual("This value went into the data file during serialization.", obj.Member2);
Assert.AreEqual("This value was set during deserialization", obj.Member3);
Assert.AreEqual("This value was set after deserialization.", obj.Member4);
}
[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
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
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.
}
}
}
#endif
@@ -0,0 +1,235 @@
#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.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
public class TypeNameHandlingTests : TestFixtureBase
{
[Test]
public void WriteTypeNameForObjects()
{
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
EmployeeReference employee = new EmployeeReference();
string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
Assert.AreEqual(@"{
""$id"": ""1"",
""$type"": """ + employeeRef + @""",
""Name"": null,
""Manager"": null
}", json);
}
[Test]
public void DeserializeTypeName()
{
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
string json = @"{
""$id"": ""1"",
""$type"": """ + employeeRef + @""",
""Name"": ""Name!"",
""Manager"": null
}";
object employee = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
Assert.IsInstanceOfType(typeof(EmployeeReference), employee);
Assert.AreEqual("Name!", ((EmployeeReference)employee).Name);
}
[Test]
public void SerializeGenericObjectListWithTypeName()
{
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
string personRef = typeof(Person).AssemblyQualifiedName;
List<object> values = new List<object>
{
new EmployeeReference
{
Name = "Bob",
Manager = new EmployeeReference {Name = "Frank"}
},
new Person
{
Department = "Department",
BirthDate = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc),
LastModified = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc)
},
"String!",
int.MinValue
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
Assert.AreEqual(@"[
{
""$id"": ""1"",
""$type"": """ + employeeRef + @""",
""Name"": ""Bob"",
""Manager"": {
""$id"": ""2"",
""$type"": """ + employeeRef + @""",
""Name"": ""Frank"",
""Manager"": null
}
},
{
""$type"": """ + personRef + @""",
""Name"": null,
""BirthDate"": ""\/Date(978134400000)\/"",
""LastModified"": ""\/Date(978134400000)\/""
},
""String!"",
-2147483648
]", json);
}
[Test]
public void DeserializeGenericObjectListWithTypeName()
{
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
string personRef = typeof(Person).AssemblyQualifiedName;
string json = @"[
{
""$id"": ""1"",
""$type"": """ + employeeRef + @""",
""Name"": ""Bob"",
""Manager"": {
""$id"": ""2"",
""$type"": """ + employeeRef + @""",
""Name"": ""Frank"",
""Manager"": null
}
},
{
""$type"": """ + personRef + @""",
""Name"": null,
""BirthDate"": ""\/Date(978134400000)\/"",
""LastModified"": ""\/Date(978134400000)\/""
},
""String!"",
-2147483648
]";
List<object> values = (List<object>)JsonConvert.DeserializeObject(json, typeof(List<object>), new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
Assert.AreEqual(4, values.Count);
EmployeeReference e = (EmployeeReference)values[0];
Person p = (Person)values[1];
Assert.AreEqual("Bob", e.Name);
Assert.AreEqual("Frank", e.Manager.Name);
Assert.AreEqual(null, p.Name);
Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.BirthDate);
Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.LastModified);
Assert.AreEqual("String!", values[2]);
Assert.AreEqual(int.MinValue, values[3]);
}
[Test]
[ExpectedException(typeof(JsonSerializationException))]
public void DeserializeWithBadTypeName()
{
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
string json = @"{
""$id"": ""1"",
""$type"": """ + employeeRef + @""",
""Name"": ""Name!"",
""Manager"": null
}";
JsonConvert.DeserializeObject(json, typeof(Person), new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
}
[Test]
public void DeserializeTypeNameWithNoTypeNameHandling()
{
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
string json = @"{
""$id"": ""1"",
""$type"": """ + employeeRef + @""",
""Name"": ""Name!"",
""Manager"": null
}";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
Assert.AreEqual(@"{
""Name"": ""Name!"",
""Manager"": null
}", o.ToString());
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved.")]
public void DeserializeTypeNameOnly()
{
string json = @"{
""$id"": ""1"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee"",
""Name"": ""Name!"",
""Manager"": null
}";
JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
}
}
}