-Fixed potential race condition serializing F# objects

-Fixed schema divisible sometimes incorrectly validating to false
-Fixed not calling virtual ShouldSerialize methods
This commit is contained in:
James Newton-King
2014-03-31 15:47:36 +13:00
parent de5f7dd8a8
commit 6965fcfa46
63 changed files with 4992 additions and 3302 deletions
@@ -0,0 +1,599 @@
#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.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class ExtensionDataTests : TestFixtureBase
{
public class ExtensionDataDeserializeWithNonDefaultConstructor
{
public ExtensionDataDeserializeWithNonDefaultConstructor(string name)
{
Name = name;
}
[JsonExtensionData]
public IDictionary<string, JToken> _extensionData;
public string Name { get; set; }
}
[Test]
public void ExtensionDataDeserializeWithNonDefaultConstructorTest()
{
ExtensionDataDeserializeWithNonDefaultConstructor c = new ExtensionDataDeserializeWithNonDefaultConstructor("Name!");
c._extensionData = new Dictionary<string, JToken>
{
{ "Key!", "Value!" }
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"{
""Name"": ""Name!"",
""Key!"": ""Value!""
}", json);
var c2 = JsonConvert.DeserializeObject<ExtensionDataDeserializeWithNonDefaultConstructor>(json);
Assert.AreEqual("Name!", c2.Name);
Assert.IsNotNull(c2._extensionData);
Assert.AreEqual(1, c2._extensionData.Count);
Assert.AreEqual("Value!", (string)c2._extensionData["Key!"]);
}
[Test]
public void ExtensionDataWithNull()
{
string json = @"{
'TaxRate': 0.125,
'a':null
}";
var invoice = JsonConvert.DeserializeObject<ExtendedObject>(json);
Assert.AreEqual(JTokenType.Null, invoice._additionalData["a"].Type);
Assert.AreEqual(typeof(double), ((JValue)invoice._additionalData["TaxRate"]).Value.GetType());
string result = JsonConvert.SerializeObject(invoice);
Assert.AreEqual(@"{""TaxRate"":0.125,""a"":null}", result);
}
[Test]
public void ExtensionDataFloatParseHandling()
{
string json = @"{
'TaxRate': 0.125,
'a':null
}";
var invoice = JsonConvert.DeserializeObject<ExtendedObject>(json, new JsonSerializerSettings
{
FloatParseHandling = FloatParseHandling.Decimal
});
Assert.AreEqual(typeof(decimal), ((JValue)invoice._additionalData["TaxRate"]).Value.GetType());
}
#pragma warning disable 649
class ExtendedObject
{
[JsonExtensionData]
internal IDictionary<string, JToken> _additionalData;
}
#pragma warning restore 649
#pragma warning disable 169
public class CustomerInvoice
{
// we're only modifing the tax rate
public decimal TaxRate { get; set; }
// everything else gets stored here
[JsonExtensionData]
private IDictionary<string, JToken> _additionalData;
}
#pragma warning restore 169
[Test]
public void ExtensionDataExample()
{
string json = @"{
'HourlyRate': 150,
'Hours': 40,
'TaxRate': 0.125
}";
var invoice = JsonConvert.DeserializeObject<CustomerInvoice>(json);
// increase tax to 15%
invoice.TaxRate = 0.15m;
string result = JsonConvert.SerializeObject(invoice);
// {
// 'TaxRate': 0.15,
// 'HourlyRate': 150,
// 'Hours': 40
// }
Assert.AreEqual(@"{""TaxRate"":0.15,""HourlyRate"":150,""Hours"":40}", result);
}
public class ExtensionDataTestClass
{
public string Name { get; set; }
[JsonProperty("custom_name")]
public string CustomName { get; set; }
[JsonIgnore]
public IList<int> Ignored { get; set; }
public bool GetPrivate { get; internal set; }
public bool GetOnly
{
get { return true; }
}
public readonly string Readonly = "Readonly";
public IList<int> Ints { get; set; }
[JsonExtensionData]
internal IDictionary<string, JToken> ExtensionData { get; set; }
public ExtensionDataTestClass()
{
Ints = new List<int> { 0 };
}
}
public class JObjectExtensionDataTestClass
{
public string Name { get; set; }
[JsonExtensionData]
public JObject ExtensionData { get; set; }
}
[Test]
public void RoundTripJObjectExtensionData()
{
JObjectExtensionDataTestClass c = new JObjectExtensionDataTestClass();
c.Name = "Name!";
c.ExtensionData = new JObject
{
{ "one", 1 },
{ "two", "II" },
{ "three", new JArray(1, 1, 1) }
};
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
JObjectExtensionDataTestClass c2 = JsonConvert.DeserializeObject<JObjectExtensionDataTestClass>(json);
Assert.AreEqual("Name!", c2.Name);
Assert.IsTrue(JToken.DeepEquals(c.ExtensionData, c2.ExtensionData));
}
[Test]
public void ExtensionDataTest()
{
string json = @"{
""Ints"": [1,2,3],
""Ignored"": [1,2,3],
""Readonly"": ""Readonly"",
""Name"": ""Actually set!"",
""CustomName"": ""Wrong name!"",
""GetPrivate"": true,
""GetOnly"": true,
""NewValueSimple"": true,
""NewValueComplex"": [1,2,3]
}";
ExtensionDataTestClass c = JsonConvert.DeserializeObject<ExtensionDataTestClass>(json);
Assert.AreEqual("Actually set!", c.Name);
Assert.AreEqual(4, c.Ints.Count);
Assert.AreEqual("Readonly", (string)c.ExtensionData["Readonly"]);
Assert.AreEqual("Wrong name!", (string)c.ExtensionData["CustomName"]);
Assert.AreEqual(true, (bool)c.ExtensionData["GetPrivate"]);
Assert.AreEqual(true, (bool)c.ExtensionData["GetOnly"]);
Assert.AreEqual(true, (bool)c.ExtensionData["NewValueSimple"]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["NewValueComplex"]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), c.ExtensionData["Ignored"]));
Assert.AreEqual(7, c.ExtensionData.Count);
}
public class MultipleExtensionDataAttributesTestClass
{
public string Name { get; set; }
[JsonExtensionData]
internal IDictionary<string, JToken> ExtensionData1 { get; set; }
[JsonExtensionData]
internal IDictionary<string, JToken> ExtensionData2 { get; set; }
}
public class ExtensionDataAttributesInheritanceTestClass : MultipleExtensionDataAttributesTestClass
{
[JsonExtensionData]
internal IDictionary<string, JToken> ExtensionData0 { get; set; }
}
public class FieldExtensionDataAttributeTestClass
{
[JsonExtensionData]
internal IDictionary<object, object> ExtensionData;
}
public class PublicExtensionDataAttributeTestClass
{
public string Name { get; set; }
[JsonExtensionData]
public IDictionary<object, object> ExtensionData;
}
public class PublicExtensionDataAttributeTestClassWithNonDefaultConstructor
{
public string Name { get; set; }
public PublicExtensionDataAttributeTestClassWithNonDefaultConstructor(string name)
{
Name = name;
}
[JsonExtensionData]
public IDictionary<object, object> ExtensionData;
}
public class PublicNoReadExtensionDataAttributeTestClass
{
public string Name { get; set; }
[JsonExtensionData(ReadData = false)]
public IDictionary<object, object> ExtensionData;
}
public class PublicNoWriteExtensionDataAttributeTestClass
{
public string Name { get; set; }
[JsonExtensionData(WriteData = false)]
public IDictionary<object, object> ExtensionData;
}
public class PublicJTokenExtensionDataAttributeTestClass
{
public string Name { get; set; }
[JsonExtensionData]
public IDictionary<string, JToken> ExtensionData;
}
[Test]
public void DeserializeDirectoryAccount()
{
string json = @"{'DisplayName':'John Smith', 'SAMAccountName':'contoso\\johns'}";
DirectoryAccount account = JsonConvert.DeserializeObject<DirectoryAccount>(json);
Assert.AreEqual("John Smith", account.DisplayName);
Assert.AreEqual("contoso", account.Domain);
Assert.AreEqual("johns", account.UserName);
}
[Test]
public void SerializePublicExtensionData()
{
string json = JsonConvert.SerializeObject(new PublicExtensionDataAttributeTestClass
{
Name = "Name!",
ExtensionData = new Dictionary<object, object>
{
{ "Test", 1 }
}
});
Assert.AreEqual(@"{""Name"":""Name!"",""Test"":1}", json);
}
[Test]
public void SerializePublicExtensionDataNull()
{
string json = JsonConvert.SerializeObject(new PublicExtensionDataAttributeTestClass
{
Name = "Name!"
});
Assert.AreEqual(@"{""Name"":""Name!""}", json);
}
[Test]
public void SerializePublicNoWriteExtensionData()
{
string json = JsonConvert.SerializeObject(new PublicNoWriteExtensionDataAttributeTestClass
{
Name = "Name!",
ExtensionData = new Dictionary<object, object>
{
{ "Test", 1 }
}
});
Assert.AreEqual(@"{""Name"":""Name!""}", json);
}
[Test]
public void DeserializeNoReadPublicExtensionData()
{
PublicNoReadExtensionDataAttributeTestClass c = JsonConvert.DeserializeObject<PublicNoReadExtensionDataAttributeTestClass>(@"{""Name"":""Name!"",""Test"":1}");
Assert.AreEqual(null, c.ExtensionData);
}
[Test]
public void SerializePublicExtensionDataCircularReference()
{
var c = new PublicExtensionDataAttributeTestClass
{
Name = "Name!",
ExtensionData = new Dictionary<object, object>
{
{ "Test", 1 }
}
};
c.ExtensionData["Self"] = c;
string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
Formatting = Formatting.Indented
});
Assert.AreEqual(@"{
""$id"": ""1"",
""Name"": ""Name!"",
""Test"": 1,
""Self"": {
""$ref"": ""1""
}
}", json);
var c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
});
Assert.AreEqual("Name!", c2.Name);
PublicExtensionDataAttributeTestClass bizzaroC2 = (PublicExtensionDataAttributeTestClass)c2.ExtensionData["Self"];
Assert.AreEqual(c2, bizzaroC2);
Assert.AreEqual(1, (long)bizzaroC2.ExtensionData["Test"]);
}
[Test]
public void DeserializePublicJTokenExtensionDataCircularReference()
{
string json = @"{
""$id"": ""1"",
""Name"": ""Name!"",
""Test"": 1,
""Self"": {
""$ref"": ""1""
}
}";
var c2 = JsonConvert.DeserializeObject<PublicJTokenExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
});
Assert.AreEqual("Name!", c2.Name);
JObject bizzaroC2 = (JObject)c2.ExtensionData["Self"];
Assert.AreEqual("Name!", (string)bizzaroC2["Name"]);
Assert.AreEqual(1, (int)bizzaroC2["Test"]);
Assert.AreEqual(1, (int)c2.ExtensionData["Test"]);
}
[Test]
public void DeserializePublicExtensionDataTypeNamdHandling()
{
string json = @"{
""$id"": ""1"",
""Name"": ""Name!"",
""Test"": 1,
""Self"": {
""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
""HourlyWage"": 2.0,
""Name"": null,
""BirthDate"": ""0001-01-01T00:00:00"",
""LastModified"": ""0001-01-01T00:00:00""
}
}";
PublicExtensionDataAttributeTestClass c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
Assert.AreEqual("Name!", c2.Name);
WagePerson bizzaroC2 = (WagePerson)c2.ExtensionData["Self"];
Assert.AreEqual(2m, bizzaroC2.HourlyWage);
}
[Test]
public void DeserializePublicExtensionDataTypeNamdHandlingNonDefaultConstructor()
{
string json = @"{
""$id"": ""1"",
""Name"": ""Name!"",
""Test"": 1,
""Self"": {
""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
""HourlyWage"": 2.0,
""Name"": null,
""BirthDate"": ""0001-01-01T00:00:00"",
""LastModified"": ""0001-01-01T00:00:00""
}
}";
PublicExtensionDataAttributeTestClassWithNonDefaultConstructor c2 = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClassWithNonDefaultConstructor>(json, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
Assert.AreEqual("Name!", c2.Name);
WagePerson bizzaroC2 = (WagePerson)c2.ExtensionData["Self"];
Assert.AreEqual(2m, bizzaroC2.HourlyWage);
}
[Test]
public void SerializePublicExtensionDataTypeNamdHandling()
{
PublicExtensionDataAttributeTestClass c = new PublicExtensionDataAttributeTestClass
{
Name = "Name!",
ExtensionData = new Dictionary<object, object>
{
{
"Test", new WagePerson
{
HourlyWage = 2.1m
}
}
}
};
string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
Formatting = Formatting.Indented
});
Assert.AreEqual(@"{
""$type"": ""Newtonsoft.Json.Tests.Serialization.ExtensionDataTests+PublicExtensionDataAttributeTestClass, Newtonsoft.Json.Tests"",
""Name"": ""Name!"",
""Test"": {
""$type"": ""Newtonsoft.Json.Tests.TestObjects.WagePerson, Newtonsoft.Json.Tests"",
""HourlyWage"": 2.1,
""Name"": null,
""BirthDate"": ""0001-01-01T00:00:00"",
""LastModified"": ""0001-01-01T00:00:00""
}
}", json);
}
[Test]
public void DeserializePublicExtensionData()
{
string json = @"{
'Name':'Name!',
'NoMatch':'NoMatch!',
'ExtensionData':{'HAI':true}
}";
var c = JsonConvert.DeserializeObject<PublicExtensionDataAttributeTestClass>(json);
Assert.AreEqual("Name!", c.Name);
Assert.AreEqual(2, c.ExtensionData.Count);
Assert.AreEqual("NoMatch!", (string)c.ExtensionData["NoMatch"]);
// the ExtensionData property is put into the extension data
// inception
var o = (JObject)c.ExtensionData["ExtensionData"];
Assert.AreEqual(1, o.Count);
Assert.IsTrue(JToken.DeepEquals(new JObject { { "HAI", true } }, o));
}
[Test]
public void FieldExtensionDataAttributeTest_Serialize()
{
FieldExtensionDataAttributeTestClass c = new FieldExtensionDataAttributeTestClass
{
ExtensionData = new Dictionary<object, object>()
};
string json = JsonConvert.SerializeObject(c);
Assert.AreEqual("{}", json);
}
[Test]
public void FieldExtensionDataAttributeTest_Deserialize()
{
var c = JsonConvert.DeserializeObject<FieldExtensionDataAttributeTestClass>("{'first':1,'second':2}");
Assert.AreEqual(2, c.ExtensionData.Count);
Assert.AreEqual(1, (long)c.ExtensionData["first"]);
Assert.AreEqual(2, (long)c.ExtensionData["second"]);
}
[Test]
public void MultipleExtensionDataAttributesTest()
{
var c = JsonConvert.DeserializeObject<MultipleExtensionDataAttributesTestClass>("{'first':[1],'second':[2]}");
Assert.AreEqual(null, c.ExtensionData1);
Assert.AreEqual(2, c.ExtensionData2.Count);
Assert.AreEqual(1, (int)((JArray)c.ExtensionData2["first"])[0]);
Assert.AreEqual(2, (int)((JArray)c.ExtensionData2["second"])[0]);
}
[Test]
public void ExtensionDataAttributesInheritanceTest()
{
var c = JsonConvert.DeserializeObject<ExtensionDataAttributesInheritanceTestClass>("{'first':1,'second':2}");
Assert.AreEqual(null, c.ExtensionData1);
Assert.AreEqual(null, c.ExtensionData2);
Assert.AreEqual(2, c.ExtensionData0.Count);
Assert.AreEqual(1, (int)c.ExtensionData0["first"]);
Assert.AreEqual(2, (int)c.ExtensionData0["second"]);
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,543 @@
#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.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json.Serialization;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class ShouldSerializeTests : TestFixtureBase
{
[Test]
public void VirtualShouldSerialize()
{
var setFoo = new Foo1()
{
name = Guid.NewGuid().ToString(),
myBar = new Bar1()
{
name = Guid.NewGuid().ToString(),
myBaz = new Baz1[] {
new Baz1(){
name = Guid.NewGuid().ToString(),
myFrob = new Frob1[]{
new Frob1{name = Guid.NewGuid().ToString()}
}
},
new Baz1(){
name = Guid.NewGuid().ToString(),
myFrob = new Frob1[]{
new Frob1{name = Guid.NewGuid().ToString()}
}
},
new Baz1(){
name = Guid.NewGuid().ToString(),
myFrob = new Frob1[]{
new Frob1{name = Guid.NewGuid().ToString()}
}
},
}
}
};
var setFooJson = Serialize(setFoo);
var deserializedSetFoo = JsonConvert.DeserializeObject<Foo1>(setFooJson);
Assert.AreEqual(setFoo.name, deserializedSetFoo.name);
Assert.NotNull(deserializedSetFoo.myBar);
Assert.AreEqual(setFoo.myBar.name, deserializedSetFoo.myBar.name);
Assert.NotNull(deserializedSetFoo.myBar.myBaz);
Assert.AreEqual(setFoo.myBar.myBaz.Length, deserializedSetFoo.myBar.myBaz.Length);
Assert.AreEqual(setFoo.myBar.myBaz[0].name, deserializedSetFoo.myBar.myBaz[0].name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz[0].myFrob[0]);
Assert.AreEqual(setFoo.myBar.myBaz[0].myFrob[0].name, deserializedSetFoo.myBar.myBaz[0].myFrob[0].name);
Assert.AreEqual(setFoo.myBar.myBaz[1].name, deserializedSetFoo.myBar.myBaz[1].name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz[2].myFrob[0]);
Assert.AreEqual(setFoo.myBar.myBaz[1].myFrob[0].name, deserializedSetFoo.myBar.myBaz[1].myFrob[0].name);
Assert.AreEqual(setFoo.myBar.myBaz[2].name, deserializedSetFoo.myBar.myBaz[2].name);
Assert.IsNotNull(deserializedSetFoo.myBar.myBaz[2].myFrob[0]);
Assert.AreEqual(setFoo.myBar.myBaz[2].myFrob[0].name, deserializedSetFoo.myBar.myBaz[2].myFrob[0].name);
Assert.AreEqual(true, setFoo.myBar.ShouldSerializemyBazCalled);
}
private string Serialize(Foo1 f)
{
//Code copied from JsonConvert.SerializeObject(), with addition of trace writing
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault();
var traceWriter = new MemoryTraceWriter();
jsonSerializer.TraceWriter = traceWriter;
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.None;
jsonSerializer.Serialize(jsonWriter, f, typeof(Foo1));
}
Console.Out.WriteLine("Trace output:\n{0}", traceWriter.ToString());
return sw.ToString();
}
[Test]
public void ShouldSerializeTest()
{
ShouldSerializeTestClass c = new ShouldSerializeTestClass();
c.Name = "James";
c.Age = 27;
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"{
""Age"": 27
}", json);
c._shouldSerializeName = true;
json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"{
""Name"": ""James"",
""Age"": 27
}", json);
ShouldSerializeTestClass deserialized = JsonConvert.DeserializeObject<ShouldSerializeTestClass>(json);
Assert.AreEqual("James", deserialized.Name);
Assert.AreEqual(27, deserialized.Age);
}
[Test]
public void ShouldSerializeExample()
{
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike;
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
Console.WriteLine(json);
}
[Test]
public void SpecifiedTest()
{
SpecifiedTestClass c = new SpecifiedTestClass();
c.Name = "James";
c.Age = 27;
c.NameSpecified = false;
string json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"{
""Age"": 27
}", json);
SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
Assert.IsNull(deserialized.Name);
Assert.IsFalse(deserialized.NameSpecified);
Assert.IsFalse(deserialized.WeightSpecified);
Assert.IsFalse(deserialized.HeightSpecified);
Assert.IsFalse(deserialized.FavoriteNumberSpecified);
Assert.AreEqual(27, deserialized.Age);
c.NameSpecified = true;
c.WeightSpecified = true;
c.HeightSpecified = true;
c.FavoriteNumber = 23;
json = JsonConvert.SerializeObject(c, Formatting.Indented);
Assert.AreEqual(@"{
""Name"": ""James"",
""Age"": 27,
""Weight"": 0,
""Height"": 0,
""FavoriteNumber"": 23
}", json);
deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json);
Assert.AreEqual("James", deserialized.Name);
Assert.IsTrue(deserialized.NameSpecified);
Assert.IsTrue(deserialized.WeightSpecified);
Assert.IsTrue(deserialized.HeightSpecified);
Assert.IsTrue(deserialized.FavoriteNumberSpecified);
Assert.AreEqual(27, deserialized.Age);
Assert.AreEqual(23, deserialized.FavoriteNumber);
}
// [Test]
// public void XmlSerializerSpecifiedTrueTest()
// {
// XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
// StringWriter sw = new StringWriter();
// s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = true });
// Console.WriteLine(sw.ToString());
// string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
//<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
// <FirstOrder>First</FirstOrder>
//</OptionalOrder>";
// OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
// Console.WriteLine(o.FirstOrder);
// Console.WriteLine(o.FirstOrderSpecified);
// }
// [Test]
// public void XmlSerializerSpecifiedFalseTest()
// {
// XmlSerializer s = new XmlSerializer(typeof(OptionalOrder));
// StringWriter sw = new StringWriter();
// s.Serialize(sw, new OptionalOrder() { FirstOrder = "First", FirstOrderSpecified = false });
// Console.WriteLine(sw.ToString());
// // string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
// //<OptionalOrder xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
// // <FirstOrder>First</FirstOrder>
// //</OptionalOrder>";
// // OptionalOrder o = (OptionalOrder)s.Deserialize(new StringReader(xml));
// // Console.WriteLine(o.FirstOrder);
// // Console.WriteLine(o.FirstOrderSpecified);
// }
public class OptionalOrder
{
// This field shouldn't be serialized
// if it is uninitialized.
public string FirstOrder;
// Use the XmlIgnoreAttribute to ignore the
// special field named "FirstOrderSpecified".
[System.Xml.Serialization.XmlIgnoreAttribute]
public bool FirstOrderSpecified;
}
public class FamilyDetails
{
public string Name { get; set; }
public int NumberOfChildren { get; set; }
[JsonIgnore]
public bool NumberOfChildrenSpecified { get; set; }
}
[Test]
public void SpecifiedExample()
{
FamilyDetails joe = new FamilyDetails();
joe.Name = "Joe Family Details";
joe.NumberOfChildren = 4;
joe.NumberOfChildrenSpecified = true;
FamilyDetails martha = new FamilyDetails();
martha.Name = "Martha Family Details";
martha.NumberOfChildren = 3;
martha.NumberOfChildrenSpecified = false;
string json = JsonConvert.SerializeObject(new[] { joe, martha }, Formatting.Indented);
//[
// {
// "Name": "Joe Family Details",
// "NumberOfChildren": 4
// },
// {
// "Name": "Martha Family Details"
// }
//]
Console.WriteLine(json);
string mikeString = "{\"Name\": \"Mike Person\"}";
FamilyDetails mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeString);
Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
string mikeFullDisclosureString = "{\"Name\": \"Mike Person\", \"NumberOfChildren\": \"0\"}";
mike = JsonConvert.DeserializeObject<FamilyDetails>(mikeFullDisclosureString);
Console.WriteLine("mikeString specifies number of children: {0}", mike.NumberOfChildrenSpecified);
}
[Test]
public void ShouldSerializeInheritedClassTest()
{
NewEmployee joe = new NewEmployee();
joe.Name = "Joe Employee";
joe.Age = 100;
Employee mike = new Employee();
mike.Name = "Mike Manager";
mike.Manager = mike;
joe.Manager = mike;
//StringWriter sw = new StringWriter();
//XmlSerializer x = new XmlSerializer(typeof(NewEmployee));
//x.Serialize(sw, joe);
//Console.WriteLine(sw);
//JavaScriptSerializer s = new JavaScriptSerializer();
//Console.WriteLine(s.Serialize(new {html = @"<script>hi</script>; & ! ^ * ( ) ! @ # $ % ^ ' "" - , . / ; : [ { } ] ; ' - _ = + ? ` ~ \ |"}));
string json = JsonConvert.SerializeObject(joe, Formatting.Indented);
Assert.AreEqual(@"{
""Age"": 100,
""Name"": ""Joe Employee"",
""Manager"": {
""Name"": ""Mike Manager""
}
}", json);
}
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
return (Manager != this);
}
}
public class NewEmployee : Employee
{
public int Age { get; set; }
public bool ShouldSerializeName()
{
return false;
}
}
}
public class ShouldSerializeTestClass
{
internal bool _shouldSerializeName;
public string Name { get; set; }
public int Age { get; set; }
public void ShouldSerializeAge()
{
// dummy. should never be used because it doesn't return bool
}
public bool ShouldSerializeName()
{
return _shouldSerializeName;
}
}
public class SpecifiedTestClass
{
private bool _nameSpecified;
public string Name { get; set; }
public int Age { get; set; }
public int Weight { get; set; }
public int Height { get; set; }
public int FavoriteNumber { get; set; }
// dummy. should never be used because it isn't of type bool
[JsonIgnore]
public long AgeSpecified { get; set; }
[JsonIgnore]
public bool NameSpecified
{
get { return _nameSpecified; }
set { _nameSpecified = value; }
}
[JsonIgnore]
public bool WeightSpecified;
[JsonIgnore]
[System.Xml.Serialization.XmlIgnoreAttribute]
public bool HeightSpecified;
[JsonIgnore]
public bool FavoriteNumberSpecified
{
// get only example
get { return FavoriteNumber != 0; }
}
}
public class Foo1
{
private Bar1 myBarField;
public Bar1 myBar
{
get
{
return myBarField;
}
set { myBarField = value; }
}
private string nameField;
public string name
{
get
{
return nameField;
}
set
{
nameField = value;
}
}
public virtual bool ShouldSerializemyBar()
{
return (myBar != null);
}
public virtual bool ShouldSerializename()
{
return (name != null);
}
}
public class Bar1
{
[JsonIgnore]
public bool ShouldSerializemyBazCalled { get; set;}
private Baz1[] myBazField;
public Baz1[] myBaz
{
get
{
return myBazField;
}
set { myBazField = value; }
}
private string nameField;
public string name
{
get
{
return nameField;
}
set
{
nameField = value;
}
}
public virtual bool ShouldSerializemyBaz()
{
ShouldSerializemyBazCalled = true;
return (myBaz != null);
}
public virtual bool ShouldSerializename()
{
return (name != null);
}
}
public class Baz1
{
private Frob1[] myFrobField;
public Frob1[] myFrob
{
get
{
return myFrobField;
}
set { myFrobField = value; }
}
private string nameField;
public string name
{
get
{
return nameField;
}
set { nameField = value; }
}
public virtual bool ShouldSerializename()
{
return (name != null);
}
public virtual bool ShouldSerializemyFrob()
{
return (myFrob != null);
}
}
public class Frob1
{
private string nameField;
public string name
{
get
{
return nameField;
}
set { nameField = value; }
}
public virtual bool ShouldSerializename()
{
return (name != null);
}
}
}
@@ -1173,7 +1173,7 @@ namespace Newtonsoft.Json.Tests.Serialization
string json = JsonConvert.SerializeObject(l, Formatting.Indented);
Assert.AreEqual(@"[
{
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 0
},
{
@@ -1208,7 +1208,7 @@ namespace Newtonsoft.Json.Tests.Serialization
string json = JsonConvert.SerializeObject(l, Formatting.Indented);
Assert.AreEqual(@"{
""First"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""Second"": ""String!"",
@@ -1238,7 +1238,7 @@ namespace Newtonsoft.Json.Tests.Serialization
string json = JsonConvert.SerializeObject(o1, Formatting.Indented);
string expected = @"{
""Object1"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""Object2"": 123,
@@ -1279,7 +1279,7 @@ namespace Newtonsoft.Json.Tests.Serialization
1,
""two"",
{
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
}
]
@@ -1317,7 +1317,7 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(@"{
""Data"": [
{
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
{
@@ -1342,14 +1342,14 @@ namespace Newtonsoft.Json.Tests.Serialization
json = @"{
""Data"": [
{
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
{
""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
""$values"": [
{
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
}
]
@@ -1396,7 +1396,7 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(@"{
""Data"": {
""one"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""two"": {
@@ -1419,13 +1419,13 @@ namespace Newtonsoft.Json.Tests.Serialization
json = @"{
""Data"": {
""one"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""two"": {
""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
""one"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
}
}
@@ -1479,7 +1479,7 @@ namespace Newtonsoft.Json.Tests.Serialization
]
},
""Prop2"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""Prop3"": 3,
@@ -1527,7 +1527,7 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual(@"{
""Data"": {
""one"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""two"": {
@@ -1554,13 +1554,13 @@ namespace Newtonsoft.Json.Tests.Serialization
json = @"{
""Data"": {
""one"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 1
},
""two"": {
""$type"": ""Newtonsoft.Json.Tests.Linq.DynamicDictionary, Newtonsoft.Json.Tests"",
""one"": {
""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
""$type"": ""Newtonsoft.Json.Tests.TestObjects.TestComponentSimple, Newtonsoft.Json.Tests"",
""MyProperty"": 2
}
}