-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
+22 -6
View File
@@ -24,13 +24,8 @@
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Newtonsoft.Json.Utilities;
using NUnit.Framework;
using System.IO;
using System.Linq;
namespace Newtonsoft.Json.Tests
{
@@ -252,7 +247,7 @@ now brown cow?", '"', true);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
string result = JsonConvert.DeserializeObject<string>(serialized);
JsonConvert.DeserializeObject<string>(serialized);
}
[Test]
@@ -286,6 +281,8 @@ now brown cow?", '"', true);
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.0", JsonConvert.ToString(1d));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(double.PositiveInfinity));
@@ -293,6 +290,25 @@ now brown cow?", '"', true);
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(double.NaN));
}
[Test]
public void DecimalToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
Assert.AreEqual("1.0", JsonConvert.ToString(1m));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(decimal.MaxValue));
Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(decimal.MinValue));
}
[Test]
public void StringEscaping()
{
+58 -820
View File
@@ -370,7 +370,7 @@ keyword such as type of business.""
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass. Use the JsonPropertyAttribute to specify another name.")]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.")]
public void BadJsonPropertyClassSerialize()
{
JsonConvert.SerializeObject(new BadJsonPropertyClass());
@@ -559,7 +559,7 @@ keyword such as type of business.""
};
string json = JsonConvert.SerializeObject(anonymous);
Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647,""NestedAnonymous"":{""NestedValue"":255},""NestedArray"":[1,2],""Product"":{""Name"":""TestProduct"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0,""Sizes"":null}}", json);
Assert.AreEqual(@"{""StringValue"":""I am a string"",""IntValue"":2147483647,""NestedAnonymous"":{""NestedValue"":255},""NestedArray"":[1,2],""Product"":{""Name"":""TestProduct"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null}}", json);
anonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);
Assert.AreEqual("I am a string", anonymous.StringValue);
@@ -588,7 +588,7 @@ keyword such as type of business.""
jsonSerializer.Serialize(sw, collection);
Assert.AreEqual(@"[{""Name"":""Test1"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0,""Sizes"":null},{""Name"":""Test2"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0,""Sizes"":null},{""Name"":""Test3"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0,""Sizes"":null}]",
Assert.AreEqual(@"[{""Name"":""Test1"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null},{""Name"":""Test2"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null},{""Name"":""Test3"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0.0,""Sizes"":null}]",
sw.GetStringBuilder().ToString());
ProductCollection collectionNew = (ProductCollection)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(sw.GetStringBuilder().ToString())), typeof(ProductCollection));
@@ -609,7 +609,7 @@ keyword such as type of business.""
//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},{""Name"":""Alien"",""ExpiryDate"":""\/Date(946684800000)\/"",""Price"":0}]}", sw.GetStringBuilder().ToString());
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);
@@ -617,7 +617,7 @@ keyword such as type of business.""
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}]}")), typeof(Store));
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);
}
@@ -877,6 +877,26 @@ keyword such as type of business.""
Assert.AreEqual(testDate, m2.MemberConverter);
}
[Test]
public void ConverterAttributeExample()
{
DateTime date = Convert.ToDateTime("1970-01-01T00:00:00Z").ToUniversalTime();
MemberConverterClass c = new MemberConverterClass
{
DefaultConverter = date,
MemberConverter = date
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Console.WriteLine(json);
//{
// "DefaultConverter": "\/Date(0)\/",
// "MemberConverter": "1970-01-01T00:00:00Z"
//}
}
[Test]
public void SerializerShouldUseMemberConverterOverClassAndArgumentConverter()
{
@@ -1656,515 +1676,12 @@ keyword such as type of business.""
Assert.AreEqual("James", p["Name"]);
}
[Test]
public void SerializeEmployeeReference()
{
Employee mikeManager = new Employee
{
Name = "Mike Manager"
};
Employee joeUser = new Employee
{
Name = "Joe User",
Manager = mikeManager
};
List<Employee> employees = new List<Employee>
{
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<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(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()
{
Employee e1 = new Employee { Name = "e1" };
Employee e2 = new Employee { Name = "e2" };
List<Employee> employees = new List<Employee> { 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<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(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()
{
Employee e1 = new Employee {Name = "e1"};
Employee e2 = new Employee {Name = "e2"};
Dictionary<string, Employee> employees = new Dictionary<string, Employee>
{
{"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, Employee> employees = JsonConvert.DeserializeObject<Dictionary<string, Employee>>(json);
Assert.AreEqual(4, employees.Count);
Employee e1 = employees["One"];
Employee e2 = employees["Two"];
Assert.AreEqual("e1", e1.Name);
Assert.AreEqual("e2", e2.Name);
Assert.AreEqual(e1, employees["Three"]);
Assert.AreEqual(e2, employees["Four"]);
}
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]
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 });
}
[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 DictionaryInterfaceClass
{
public string Name { get; set; }
public IDictionary<string, int> Dictionary { get; set; }
public ICollection<int> Collection { get; set; }
public Employee Employee { get; set; }
public EmployeeReference Employee { get; set; }
public object Random { get; set; }
public DictionaryInterfaceClass()
@@ -2179,7 +1696,7 @@ keyword such as type of business.""
2,
3
};
Employee = new Employee
Employee = new EmployeeReference
{
Name = "EmployeeName!"
};
@@ -2240,316 +1757,6 @@ keyword such as type of business.""
Assert.IsNotNull(c.Random);
}
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 WriteTypeNameForObjects()
{
string employeeRef = typeof(Employee).AssemblyQualifiedName;
Employee employee = new Employee();
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(Employee).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(Employee), employee);
Assert.AreEqual("Name!", ((Employee)employee).Name);
}
[Test]
public void SerializeGenericObjectListWithTypeName()
{
string employeeRef = typeof(Employee).AssemblyQualifiedName;
string personRef = typeof(Person).AssemblyQualifiedName;
List<object> values = new List<object>
{
new Employee
{
Name = "Bob",
Manager = new Employee {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 (Employee).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);
Employee e = (Employee) 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(Employee).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(Employee).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
});
}
[Test]
public void TypedObjectDeserializationWithComments()
{
@@ -2697,5 +1904,36 @@ keyword such as type of business.""
Assert.AreEqual("First", content.Children[0].Text);
Assert.AreEqual("Second", content.Children[1].Text);
}
public enum RoleTransferOperation
{
First,
Second
}
public enum RoleTransferDirection
{
First,
Second
}
public class RoleTransfer
{
public RoleTransferOperation Operation { get; set; } //This is enum type
public string RoleName { get; set; }
public RoleTransferDirection Direction { get; set; } //This is enum type
}
[Test]
public void RoleTransferTest()
{
string json = @"{""Operation"":""1"",""RoleName"":""Admin"",""Direction"":""0""}";
RoleTransfer r = JsonConvert.DeserializeObject<RoleTransfer>(json);
Assert.AreEqual(RoleTransferOperation.Second, r.Operation);
Assert.AreEqual("Admin", r.RoleName);
Assert.AreEqual(RoleTransferDirection.First, r.Direction);
}
}
}
@@ -63,11 +63,14 @@
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Linq\JTokenReaderTest.cs" />
<Compile Include="Linq\JTokenWriterTest.cs" />
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
@@ -80,7 +83,7 @@
<Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\Employee.cs" />
<Compile Include="TestObjects\EmployeeReference.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GenericListAndDictionaryInterfaceProperties.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
@@ -97,6 +100,10 @@
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\PrivateMembersClass.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SerializationEventTestDictionary.cs" />
<Compile Include="TestObjects\SerializationEventTestList.cs" />
<Compile Include="TestObjects\SerializationEventTestObject.cs" />
<Compile Include="TestObjects\SerializationEventTestObjectWithConstructor.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
<Compile Include="TestObjects\ArticleCollection.cs" />
@@ -67,11 +67,14 @@
<Compile Include="Converters\StringEnumConverterTests.cs" />
<Compile Include="Linq\JTokenReaderTest.cs" />
<Compile Include="Linq\JTokenWriterTest.cs" />
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="JsonValidatingReaderTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
@@ -84,7 +87,7 @@
<Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
<Compile Include="TestObjects\Employee.cs" />
<Compile Include="TestObjects\EmployeeReference.cs" />
<Compile Include="TestObjects\GenericImpl.cs" />
<Compile Include="TestObjects\GenericListAndDictionaryInterfaceProperties.cs" />
<Compile Include="TestObjects\GetOnlyPropertyClass.cs" />
@@ -101,6 +104,10 @@
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\PrivateMembersClass.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SerializationEventTestDictionary.cs" />
<Compile Include="TestObjects\SerializationEventTestList.cs" />
<Compile Include="TestObjects\SerializationEventTestObject.cs" />
<Compile Include="TestObjects\SerializationEventTestObjectWithConstructor.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
<Compile Include="TestObjects\ArticleCollection.cs" />
@@ -98,10 +98,13 @@
</Compile>
<Compile Include="LinqToSql\LinqToSqlClassesSerializationTests.cs" />
<Compile Include="LinqToSql\Person.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Schema\ExtensionsTests.cs" />
<Compile Include="Schema\JsonSchemaModelBuilderTests.cs" />
<Compile Include="Schema\JsonSchemaNodeTests.cs" />
<Compile Include="Serialization\CamelCaseMappingResolverTests.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolverTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
<Compile Include="TestObjects\AbstractGenericBase.cs" />
<Compile Include="TestObjects\ArgumentConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\BadJsonPropertyClass.cs" />
@@ -112,7 +115,7 @@
<Compile Include="TestObjects\ConverterPrecedenceClass.cs" />
<Compile Include="TestObjects\ConverterPrecedenceClassConverter.cs" />
<Compile Include="TestObjects\CircularReferenceWithIdClass.cs" />
<Compile Include="TestObjects\Employee.cs" />
<Compile Include="TestObjects\EmployeeReference.cs" />
<Compile Include="TestObjects\JsonPropertyWithHandlingValues.cs" />
<Compile Include="TestObjects\DefaultValueAttributeTestClass.cs" />
<Compile Include="TestObjects\DoubleClass.cs" />
@@ -131,6 +134,10 @@
<Compile Include="TestObjects\PhoneNumber.cs" />
<Compile Include="TestObjects\PrivateMembersClass.cs" />
<Compile Include="TestObjects\RequiredMembersClass.cs" />
<Compile Include="TestObjects\SerializationEventTestDictionary.cs" />
<Compile Include="TestObjects\SerializationEventTestList.cs" />
<Compile Include="TestObjects\SerializationEventTestObject.cs" />
<Compile Include="TestObjects\SerializationEventTestObjectWithConstructor.cs" />
<Compile Include="TestObjects\SetOnlyPropertyClass.cs" />
<Compile Include="TestObjects\Article.cs" />
<Compile Include="TestObjects\ArticleCollection.cs" />
@@ -281,27 +281,14 @@ namespace Newtonsoft.Json.Tests.Schema
Assert.AreEqual(JsonSchemaType.String, schema.Type);
}
//public class CustomDirectoryInfoSerializer : JsonSerializer
//{
// protected override Newtonsoft.Json.Serialization.JsonMemberMappingCollection GetMemberMappings(Type objectType)
// {
// JsonMemberMappingCollection mappings = base.GetMemberMappings(objectType);
// JsonMemberMappingCollection c = new JsonMemberMappingCollection();
// CollectionUtils.AddRange(c, (IEnumerable) mappings.Where(m => m.MappingName != "Root"));
// return c;
// }
//}
public class CustomDirectoryInfoMapper : DefaultMappingResolver
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public override JsonMemberMappingCollection ResolveMappings(Type type)
protected override IList<JsonProperty> CreateProperties(JsonObjectContract contract)
{
JsonMemberMappingCollection mappings = base.ResolveMappings(type);
IList<JsonProperty> properties = base.CreateProperties(contract);
JsonMemberMappingCollection c = new JsonMemberMappingCollection();
CollectionUtils.AddRange(c, (IEnumerable)mappings.Where(m => m.PropertyName != "Root"));
JsonPropertyCollection c = new JsonPropertyCollection();
CollectionUtils.AddRange(c, (IEnumerable)properties.Where(m => m.PropertyName != "Root"));
return c;
}
@@ -381,7 +368,7 @@ namespace Newtonsoft.Json.Tests.Schema
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new IsoDateTimeConverter());
serializer.MappingResolver = new CustomDirectoryInfoMapper();
serializer.ContractResolver = new CustomDirectoryInfoMapper();
serializer.Serialize(jsonWriter, temp);
List<string> errors = new List<string>();
@@ -397,7 +384,7 @@ namespace Newtonsoft.Json.Tests.Schema
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.MappingResolver = new CamelCaseMappingResolver();
generator.ContractResolver = new CamelCasePropertyNamesContractResolver();
JsonSchema schema = generator.Generate(typeof (DirectoryInfo), true);
@@ -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
});
}
}
}
@@ -31,9 +31,9 @@ using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
[JsonObject(IsReference = true)]
public class Employee
public class EmployeeReference
{
public string Name { get; set; }
public Employee Manager { get; set; }
public EmployeeReference Manager { get; set; }
}
}
@@ -1,4 +1,29 @@
using System;
#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;
@@ -19,7 +44,12 @@ namespace Newtonsoft.Json.Tests.TestObjects
}
private string _privateString;
private int i;
private readonly int i;
internal string _internalString;
public int UseValue()
{
return i;
}
}
}
@@ -0,0 +1,82 @@
#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.Collections.Generic;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class SerializationEventTestDictionary : Dictionary<decimal, string>
{
// This member is serialized and deserialized with no change.
public int Member1 { get; private set; }
// The value of this field is set and reset during and
// after serialization.
public string Member2 { get; private set; }
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
public string Member3 { get; private set; }
// This field is set to null, but populated after deserialization.
public string Member4 { get; private set; }
public SerializationEventTestDictionary()
{
Member1 = 11;
Member2 = "Hello World!";
Member3 = "This is a nonserialized value";
Member4 = null;
}
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
Member2 = "This value went into the data file during serialization.";
Add(decimal.MaxValue, "Inserted on serializing");
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
Member2 = "This value was reset after serialization.";
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
Member3 = "This value was set during deserialization";
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Member4 = "This value was set after deserialization.";
}
}
}
#endif
@@ -0,0 +1,82 @@
#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.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class SerializationEventTestList : Collection<decimal>
{
// This member is serialized and deserialized with no change.
public int Member1 { get; private set; }
// The value of this field is set and reset during and
// after serialization.
public string Member2 { get; private set; }
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
public string Member3 { get; private set; }
// This field is set to null, but populated after deserialization.
public string Member4 { get; private set; }
public SerializationEventTestList()
{
Member1 = 11;
Member2 = "Hello World!";
Member3 = "This is a nonserialized value";
Member4 = null;
}
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
Member2 = "This value went into the data file during serialization.";
Insert(0, -1);
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
Member2 = "This value was reset after serialization.";
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
Member3 = "This value was set during deserialization";
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Member4 = "This value was set after deserialization.";
}
}
}
#endif
@@ -0,0 +1,84 @@
#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.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class SerializationEventTestObject
{
// This member is serialized and deserialized with no change.
public int Member1 { get; set; }
// The value of this field is set and reset during and
// after serialization.
public string Member2 { get; set; }
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
[JsonIgnore]
public string Member3 { get; set; }
// This field is set to null, but populated after deserialization.
public string Member4 { get; set; }
public SerializationEventTestObject()
{
Member1 = 11;
Member2 = "Hello World!";
Member3 = "This is a nonserialized value";
Member4 = null;
}
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
Member2 = "This value went into the data file during serialization.";
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
Member2 = "This value was reset after serialization.";
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
Member3 = "This value was set during deserialization";
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Member4 = "This value was set after deserialization.";
}
}
}
#endif
@@ -0,0 +1,83 @@
#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.Runtime.Serialization;
namespace Newtonsoft.Json.Tests.TestObjects
{
public class SerializationEventTestObjectWithConstructor
{
// This member is serialized and deserialized with no change.
public int Member1 { get; private set; }
// The value of this field is set and reset during and
// after serialization.
public string Member2 { get; private set; }
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
[JsonIgnore]
public string Member3 { get; private set; }
// This field is set to null, but populated after deserialization.
public string Member4 { get; private set; }
public SerializationEventTestObjectWithConstructor(int member1,
string member2,
string member4)
{
Member1 = member1;
Member2 = member2;
Member3 = "This is a nonserialized value";
Member4 = member4;
}
[OnSerializing]
internal void OnSerializingMethod(StreamingContext context)
{
Member2 = "This value went into the data file during serialization.";
}
[OnSerialized]
internal void OnSerializedMethod(StreamingContext context)
{
Member2 = "This value was reset after serialization.";
}
[OnDeserializing]
internal void OnDeserializingMethod(StreamingContext context)
{
Member3 = "This value was set during deserialization";
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
Member4 = "This value was set after deserialization.";
}
}
}
#endif