Skip to content
Browse files

Updated to 4.5.4.14907.

  • Loading branch information...
1 parent 7e40746 commit 3e698fb084a8be5b24ec121c6dafe6b71a9dcae7 @attilah committed
Showing with 7,748 additions and 1,196 deletions.
  1. +50 −0 Src/Newtonsoft.Json.All.sln
  2. +5 −5 Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs
  3. +29 −0 Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs
  4. +28 −0 Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
  5. +1 −1 Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs
  6. +3 −3 Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs
  7. +17 −17 Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs
  8. +1 −0 Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj
  9. +6 −6 Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj
  10. +34 −27 Src/Newtonsoft.Json.Tests/PerformanceTests.cs
  11. +1 −1 Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs
  12. +27 −0 Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs
  13. +448 −290 Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs
  14. +70 −2 Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs
  15. +56 −0 Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs
  16. +529 −175 Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs
  17. +8 −8 Src/Newtonsoft.Json/Bson/BsonWriter.cs
  18. +1 −1 Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs
  19. +19 −0 Src/Newtonsoft.Json/JsonException.cs
  20. +38 −5 Src/Newtonsoft.Json/JsonPropertyAttribute.cs
  21. +0 −18 Src/Newtonsoft.Json/JsonReaderException.cs
  22. +1 −1 Src/Newtonsoft.Json/JsonSerializationException.cs
  23. +1 −1 Src/Newtonsoft.Json/JsonTextWriter.cs
  24. +13 −15 Src/Newtonsoft.Json/JsonWriter.cs
  25. +24 −0 Src/Newtonsoft.Json/JsonWriterException.cs
  26. +1 −1 Src/Newtonsoft.Json/Linq/IJEnumerable.cs
  27. +18 −15 Src/Newtonsoft.Json/Linq/JContainer.cs
  28. +8 −8 Src/Newtonsoft.Json/Linq/JObject.cs
  29. +3 −3 Src/Newtonsoft.Json/Linq/JToken.cs
  30. +3 −3 Src/Newtonsoft.Json/Linq/JValue.cs
  31. +80 −83 Src/Newtonsoft.Json/Newtonsoft.Json.MonoDroid.csproj
  32. +78 −85 Src/Newtonsoft.Json/Newtonsoft.Json.MonoTouch.csproj
  33. +3 −0 Src/Newtonsoft.Json/Newtonsoft.Json.csproj
  34. +3 −3 Src/Newtonsoft.Json/Properties/AssemblyInfo.cs
  35. +1 −1 Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs
  36. +21 −12 Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs
  37. +1 −1 Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs
  38. +0 −2 Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs
  39. +27 −0 Src/Newtonsoft.Json/Serialization/JsonContainerContract.cs
  40. +1 −1 Src/Newtonsoft.Json/Serialization/JsonContract.cs
  41. +1 −2 Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs
  42. +1 −1 Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs
  43. +38 −0 Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs
  44. +31 −1 Src/Newtonsoft.Json/Serialization/JsonProperty.cs
  45. +2 −1 Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs
  46. +365 −271 Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs
  47. +104 −98 Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs
  48. +6 −6 Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs
  49. +2 −18 Src/Newtonsoft.Json/Utilities/CollectionUtils.cs
  50. +1 −1 Src/Newtonsoft.Json/Utilities/DynamicProxy.cs
  51. +1 −1 Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs
  52. +1 −1 Src/Newtonsoft.Json/Utilities/DynamicUtils.cs
  53. +1 −1 Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs
  54. +15 −0 Src/Newtonsoft.Json/Utilities/StringUtils.cs
  55. +5,521 −0 Src/Newtonsoft.Json/nunit.framework.xml
View
50 Src/Newtonsoft.Json.All.sln
@@ -0,0 +1,50 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Lib", "Lib", "{620042D9-2753-48F5-BEDE-3905248781D2}"
+ ProjectSection(SolutionItems) = preProject
+ Lib\NUnit\DotNet\nunit.framework.dll = Lib\NUnit\DotNet\nunit.framework.dll
+ Lib\NUnit\DotNet\nunit.framework.xml = Lib\NUnit\DotNet\nunit.framework.xml
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json", "Newtonsoft.Json\Newtonsoft.Json.csproj", "{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Tests", "Newtonsoft.Json.Tests\Newtonsoft.Json.Tests.csproj", "{3E6E2335-B079-4B5B-A65A-9D586914BCBB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.MonoDroid", "Newtonsoft.Json\Newtonsoft.Json.MonoDroid.csproj", "{C070929C-A786-4FBE-A2D1-FF69F4EF3F6D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.MonoTouch", "Newtonsoft.Json\Newtonsoft.Json.MonoTouch.csproj", "{12907C78-F5AB-46CA-8BB8-888E26ECFF72}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Newtonsoft.Json.Portable", "Newtonsoft.Json\Newtonsoft.Json.Portable.csproj", "{959F7F85-C98B-4876-971A-9036224578E4}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {3E6E2335-B079-4B5B-A65A-9D586914BCBB}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C070929C-A786-4FBE-A2D1-FF69F4EF3F6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C070929C-A786-4FBE-A2D1-FF69F4EF3F6D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C070929C-A786-4FBE-A2D1-FF69F4EF3F6D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C070929C-A786-4FBE-A2D1-FF69F4EF3F6D}.Release|Any CPU.Build.0 = Release|Any CPU
+ {12907C78-F5AB-46CA-8BB8-888E26ECFF72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {12907C78-F5AB-46CA-8BB8-888E26ECFF72}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {12907C78-F5AB-46CA-8BB8-888E26ECFF72}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {12907C78-F5AB-46CA-8BB8-888E26ECFF72}.Release|Any CPU.Build.0 = Release|Any CPU
+ {959F7F85-C98B-4876-971A-9036224578E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {959F7F85-C98B-4876-971A-9036224578E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {959F7F85-C98B-4876-971A-9036224578E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {959F7F85-C98B-4876-971A-9036224578E4}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
View
10 Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs
@@ -378,7 +378,7 @@ public void WriteEmptyStrings()
[Test]
public void WriteComment()
{
- ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON comment as BSON.",
+ ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON comment as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
@@ -392,7 +392,7 @@ public void WriteComment()
[Test]
public void WriteConstructor()
{
- ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON constructor as BSON.",
+ ExceptionAssert.Throws<JsonWriterException>("Cannot write JSON constructor as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
@@ -406,7 +406,7 @@ public void WriteConstructor()
[Test]
public void WriteRaw()
{
- ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON.",
+ ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
@@ -420,7 +420,7 @@ public void WriteRaw()
[Test]
public void WriteRawValue()
{
- ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON.",
+ ExceptionAssert.Throws<JsonWriterException>("Cannot write raw JSON as BSON. Path ''.",
() =>
{
MemoryStream ms = new MemoryStream();
@@ -652,7 +652,7 @@ public void WriteDateTimes()
[Test]
public void WriteValueOutsideOfObjectOrArray()
{
- ExceptionAssert.Throws<JsonWriterException>("Error writing String value. BSON must start with an Object or Array.",
+ ExceptionAssert.Throws<JsonWriterException>("Error writing String value. BSON must start with an Object or Array. Path ''.",
() =>
{
MemoryStream stream = new MemoryStream();
View
29 Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs
@@ -114,6 +114,35 @@ private XmlNode DeserializeXmlNode(string json, string deserializeRootElementNam
return node;
}
+#if !NET20
+ [Test]
+ public void SerializeEmptyDocument()
+ {
+ XmlDocument doc = new XmlDocument();
+ doc.LoadXml("<root />");
+
+ string json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);
+ Assert.AreEqual("null", json);
+
+ doc = new XmlDocument();
+ doc.LoadXml("<root></root>");
+
+ json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);
+ Assert.AreEqual("null", json);
+
+
+ XDocument doc1 = XDocument.Parse("<root />");
+
+ json = JsonConvert.SerializeXNode(doc1, Formatting.Indented, true);
+ Assert.AreEqual("null", json);
+
+ doc1 = XDocument.Parse("<root></root>");
+
+ json = JsonConvert.SerializeXNode(doc1, Formatting.Indented, true);
+ Assert.AreEqual("null", json);
+ }
+#endif
+
[Test]
public void DocumentSerializeIndented()
{
View
28 Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
@@ -721,5 +721,33 @@ public void SerializeObjectDateTimeZoneHandling()
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}
+
+ //[Test]
+ public void StackOverflowTest()
+ {
+ StringBuilder sb = new StringBuilder();
+
+ int depth = 900;
+ for (int i = 0; i < depth; i++)
+ {
+ sb.Append("{'A':");
+ }
+
+ // invalid json
+ sb.Append("{***}");
+ for (int i = 0; i < depth; i++)
+ {
+ sb.Append("}");
+ }
+
+ string json = sb.ToString();
+ JsonSerializer serializer = new JsonSerializer() { };
+ serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
+ }
+
+ public class Nest
+ {
+ public Nest A { get; set; }
+ }
}
}
View
2 Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs
@@ -2513,7 +2513,7 @@ public void ResetJsonTextReaderErrorCount()
toggleReaderError.Error = false;
Assert.IsTrue(jsonTextReader.Read());
- Assert.AreEqual(1, jsonTextReader.Value);
+ Assert.AreEqual(1L, jsonTextReader.Value);
toggleReaderError.Error = true;
View
6 Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs
@@ -174,8 +174,8 @@ public void WriteValueObjectWithNullable()
[Test]
public void WriteValueObjectWithUnsupportedValue()
{
- ExceptionAssert.Throws<ArgumentException>(
- @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.",
+ ExceptionAssert.Throws<JsonWriterException>(
+ @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''.",
() =>
{
StringWriter sw = new StringWriter();
@@ -597,7 +597,7 @@ public void WriteFloatingPointNumber()
public void BadWriteEndArray()
{
ExceptionAssert.Throws<JsonWriterException>(
- "No token to close.",
+ "No token to close. Path ''.",
() =>
{
StringBuilder sb = new StringBuilder();
View
34 Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs
@@ -712,27 +712,27 @@ public void ImprovedDynamicLinqExample()
""StockValue"": 22050.0
}", json);
}
+ }
- public class DynamicDictionary : DynamicObject
- {
- private readonly IDictionary<string, object> _values = new Dictionary<string, object>();
+ public class DynamicDictionary : DynamicObject
+ {
+ private readonly IDictionary<string, object> _values = new Dictionary<string, object>();
- public override IEnumerable<string> GetDynamicMemberNames()
- {
- return _values.Keys;
- }
+ public override IEnumerable<string> GetDynamicMemberNames()
+ {
+ return _values.Keys;
+ }
- public override bool TryGetMember(GetMemberBinder binder, out object result)
- {
- result = _values[binder.Name];
- return true;
- }
+ public override bool TryGetMember(GetMemberBinder binder, out object result)
+ {
+ result = _values[binder.Name];
+ return true;
+ }
- public override bool TrySetMember(SetMemberBinder binder, object value)
- {
- _values[binder.Name] = value;
- return true;
- }
+ public override bool TrySetMember(SetMemberBinder binder, object value)
+ {
+ _values[binder.Name] = value;
+ return true;
}
}
}
View
1 Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Metro.csproj
@@ -169,6 +169,7 @@
<Compile Include="Serialization\NullValueHandlingTests.cs" />
<Compile Include="Serialization\PopulateTests.cs" />
<Compile Include="Serialization\PreserveReferencesHandlingTests.cs" />
+ <Compile Include="Serialization\ReferenceLoopHandlingTests.cs" />
<Compile Include="Serialization\SerializationErrorHandlingTests.cs" />
<Compile Include="Serialization\SerializationEventAttributeTests.cs" />
<Compile Include="Serialization\TypeNameHandlingTests.cs" />
View
12 Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj
@@ -254,12 +254,6 @@
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.csproj">
- <Project>{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}</Project>
- <Name>Newtonsoft.Json</Name>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
<None Include="LinqToSql\LinqToSqlClasses.dbml">
<Generator>MSLinqToSQLGenerator</Generator>
<LastGenOutput>LinqToSqlClasses.designer.cs</LastGenOutput>
@@ -286,6 +280,12 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Newtonsoft.Json\Newtonsoft.Json.csproj">
+ <Project>{A9AE40FF-1A21-414A-9FE7-3BE13644CC6D}</Project>
+ <Name>Newtonsoft.Json</Name>
+ </ProjectReference>
+ </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
View
61 Src/Newtonsoft.Json.Tests/PerformanceTests.cs
@@ -93,6 +93,7 @@ public enum SerializeMethod
JsonNet,
JsonNetWithIsoConverter,
JsonNetBinary,
+ JsonNetLinq,
BinaryFormatter,
JavaScriptSerializer,
DataContractSerializer,
@@ -130,6 +131,7 @@ private void SerializeTests(object value)
BenchmarkSerializeMethod(SerializeMethod.JavaScriptSerializer, value);
BenchmarkSerializeMethod(SerializeMethod.DataContractJsonSerializer, value);
BenchmarkSerializeMethod(SerializeMethod.JsonNet, value);
+ BenchmarkSerializeMethod(SerializeMethod.JsonNetLinq, value);
BenchmarkSerializeMethod(SerializeMethod.JsonNetWithIsoConverter, value);
BenchmarkSerializeMethod(SerializeMethod.JsonNetBinary, value);
}
@@ -428,33 +430,6 @@ private static SimpleObject CreateSimpleObject()
};
}
- public string SerializeJsonNet(object value)
- {
- Type type = value.GetType();
-
- Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
-
- json.NullValueHandling = NullValueHandling.Ignore;
-
- json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
- json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
- json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
-
-
- StringWriter sw = new StringWriter();
- Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
-
- writer.Formatting = Formatting.None;
-
- writer.QuoteChar = '"';
- json.Serialize(writer, value);
-
- string output = sw.ToString();
- writer.Close();
-
- return output;
- }
-
public string SerializeWebExtensions(object value)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
@@ -506,6 +481,38 @@ private string Serialize(SerializeMethod method, object value)
case SerializeMethod.JsonNetWithIsoConverter:
json = JsonConvert.SerializeObject(value, new IsoDateTimeConverter());
break;
+ case SerializeMethod.JsonNetLinq:
+ {
+ TestClass c = value as TestClass;
+ if (c != null)
+ {
+ JObject o = new JObject(
+ new JProperty("strings", new JArray(
+ c.strings
+ )),
+ new JProperty("dictionary", new JObject(c.dictionary.Select(d => new JProperty(d.Key, d.Value)))),
+ new JProperty("Name", c.Name),
+ new JProperty("Now", c.Now),
+ new JProperty("BigNumber", c.BigNumber),
+ new JProperty("Address1", new JObject(
+ new JProperty("Street", c.Address1.Street),
+ new JProperty("Phone", c.Address1.Phone),
+ new JProperty("Entered", c.Address1.Entered))),
+ new JProperty("Addresses", new JArray(c.Addresses.Select(a =>
+ new JObject(
+ new JProperty("Street", a.Street),
+ new JProperty("Phone", a.Phone),
+ new JProperty("Entered", a.Entered)))))
+ );
+
+ json = o.ToString(Formatting.None);
+ }
+ else
+ {
+ json = string.Empty;
+ }
+ break;
+ }
case SerializeMethod.JsonNetBinary:
{
MemoryStream ms = new MemoryStream(Buffer);
View
2 Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs
@@ -72,5 +72,5 @@
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC
-[assembly: AssemblyFileVersion("4.5.4.14902")]
+[assembly: AssemblyFileVersion("4.5.4.14907")]
#endif
View
27 Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs
@@ -751,6 +751,33 @@ public void JsonPropertyWithHandlingValues()
}
}", json);
}
+
+ [Test]
+ public void GenerateForNullableInt32()
+ {
+ JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
+
+ JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass));
+ string json = jsonSchema.ToString();
+
+ Assert.AreEqual(@"{
+ ""type"": ""object"",
+ ""properties"": {
+ ""Value"": {
+ ""required"": true,
+ ""type"": [
+ ""integer"",
+ ""null""
+ ]
+ }
+ }
+}", json);
+ }
+ }
+
+ public class NullableInt32TestClass
+ {
+ public int? Value { get; set; }
}
public class DMDSLBase
View
738 Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs
448 additions, 290 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
72 Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs
@@ -104,7 +104,7 @@ public void SerializeCircularListsError()
circularList.Add(new CircularList { new CircularList { circularList } });
ExceptionAssert.Throws<JsonSerializationException>(
- "Self referencing loop detected for type '" + classRef + "'.",
+ "Self referencing loop detected with type '" + classRef + "'. Path '[2][0]'.",
() =>
{
JsonConvert.SerializeObject(circularList, Formatting.Indented);
@@ -264,7 +264,7 @@ public void SerializeCircularDictionarysError()
circularDictionary.Add("self", circularDictionary);
ExceptionAssert.Throws<JsonSerializationException>(
- @"Self referencing loop detected for type '" + classRef + "'.",
+ @"Self referencing loop detected with type '" + classRef + "'. Path ''.",
() =>
{
JsonConvert.SerializeObject(circularDictionary, Formatting.Indented);
@@ -1006,6 +1006,74 @@ public void ReferencedObjectItems()
Assert.IsTrue(ReferenceEquals(referenceObject.Component1, referenceObject.Component2));
}
+
+ [Test]
+ public void PropertyItemIsReferenceObject()
+ {
+ TestComponentSimple c1 = new TestComponentSimple();
+
+ PropertyItemIsReferenceObject o1 = new PropertyItemIsReferenceObject
+ {
+ Data = new PropertyItemIsReferenceBody
+ {
+ Prop1 = c1,
+ Prop2 = c1,
+ Data = new List<TestComponentSimple>
+ {
+ c1
+ }
+ }
+ };
+
+ string json = JsonConvert.SerializeObject(o1, Formatting.Indented);
+ Assert.AreEqual(@"{
+ ""Data"": {
+ ""Prop1"": {
+ ""$id"": ""1"",
+ ""MyProperty"": 0
+ },
+ ""Prop2"": {
+ ""$ref"": ""1""
+ },
+ ""Data"": {
+ ""$id"": ""2"",
+ ""$values"": [
+ {
+ ""MyProperty"": 0
+ }
+ ]
+ }
+ }
+}", json);
+
+ PropertyItemIsReferenceObject o2 = JsonConvert.DeserializeObject<PropertyItemIsReferenceObject>(json);
+
+ TestComponentSimple c2 = o2.Data.Prop1;
+ TestComponentSimple c3 = o2.Data.Prop2;
+ TestComponentSimple c4 = o2.Data.Data[0];
+
+ Assert.IsTrue(ReferenceEquals(c2, c3));
+ Assert.IsFalse(ReferenceEquals(c2, c4));
+ }
+ }
+
+ public class PropertyItemIsReferenceBody
+ {
+ public TestComponentSimple Prop1 { get; set; }
+ public TestComponentSimple Prop2 { get; set; }
+ public IList<TestComponentSimple> Data { get; set; }
+ }
+
+ public class PropertyItemIsReferenceObject
+ {
+ [JsonProperty(ItemIsReference = true)]
+ public PropertyItemIsReferenceBody Data { get; set; }
+ }
+
+ public class PropertyItemIsReferenceList
+ {
+ [JsonProperty(ItemIsReference = true)]
+ public IList<IList<object>> Data { get; set; }
}
[JsonArray(ItemIsReference = true)]
View
56 Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs
@@ -112,6 +112,62 @@ public void IgnoreDictionaryReferenceLoop()
});
Assert.AreEqual("{}", json);
}
+
+ [Test]
+ public void SerializePropertyItemReferenceLoopHandling()
+ {
+ PropertyItemReferenceLoopHandling c = new PropertyItemReferenceLoopHandling();
+ c.Text = "Text!";
+ c.SetData(new List<PropertyItemReferenceLoopHandling> { c });
+
+ string json = JsonConvert.SerializeObject(c, Formatting.Indented);
+
+ Assert.AreEqual(@"{
+ ""Text"": ""Text!"",
+ ""Data"": [
+ {
+ ""Text"": ""Text!"",
+ ""Data"": [
+ {
+ ""Text"": ""Text!"",
+ ""Data"": [
+ {
+ ""Text"": ""Text!"",
+ ""Data"": null
+ }
+ ]
+ }
+ ]
+ }
+ ]
+}", json);
+ }
+ }
+
+ public class PropertyItemReferenceLoopHandling
+ {
+ private IList<PropertyItemReferenceLoopHandling> _data;
+ private int _accessCount;
+
+ public string Text { get; set; }
+
+ [JsonProperty(ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize)]
+ public IList<PropertyItemReferenceLoopHandling> Data
+ {
+ get
+ {
+ if (_accessCount >= 3)
+ return null;
+
+ _accessCount++;
+ return new List<PropertyItemReferenceLoopHandling>(_data);
+ }
+ }
+
+ public void SetData(IList<PropertyItemReferenceLoopHandling> data)
+ {
+ _data = data;
+ }
}
[JsonArray(ItemReferenceLoopHandling = ReferenceLoopHandling.Ignore)]
View
704 Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs
@@ -24,6 +24,10 @@
#endregion
#if !PORTABLE
+#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
+using System.Dynamic;
+#endif
+using Newtonsoft.Json.Tests.Linq;
using global::System;
using global::System.Collections;
using global::System.Collections.Generic;
@@ -65,13 +69,13 @@ public void SerializeWrapper()
};
wrapper.Dictionary = new Dictionary<string, EmployeeReference>
{
- { "First", new EmployeeReference() }
+ {"First", new EmployeeReference()}
};
string json = JsonConvert.SerializeObject(wrapper, Formatting.Indented, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Auto
- });
+ {
+ TypeNameHandling = TypeNameHandling.Auto
+ });
Assert.AreEqual(@"{
""Array"": [
@@ -91,21 +95,21 @@ public void SerializeWrapper()
}", json);
Wrapper w2 = JsonConvert.DeserializeObject<Wrapper>(json);
- CustomAssert.IsInstanceOfType(typeof(List<EmployeeReference>), w2.Array);
- CustomAssert.IsInstanceOfType(typeof(Dictionary<string, EmployeeReference>), w2.Dictionary);
+ CustomAssert.IsInstanceOfType(typeof (List<EmployeeReference>), w2.Array);
+ CustomAssert.IsInstanceOfType(typeof (Dictionary<string, EmployeeReference>), w2.Dictionary);
}
[Test]
public void WriteTypeNameForObjects()
{
- string employeeRef = ReflectionUtils.GetTypeName(typeof(EmployeeReference), FormatterAssemblyStyle.Simple);
+ string employeeRef = ReflectionUtils.GetTypeName(typeof (EmployeeReference), FormatterAssemblyStyle.Simple);
EmployeeReference employee = new EmployeeReference();
string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects
- });
+ {
+ TypeNameHandling = TypeNameHandling.Objects
+ });
Assert.AreEqual(@"{
""$id"": ""1"",
@@ -118,7 +122,7 @@ public void WriteTypeNameForObjects()
[Test]
public void DeserializeTypeName()
{
- string employeeRef = ReflectionUtils.GetTypeName(typeof(EmployeeReference), FormatterAssemblyStyle.Simple);
+ string employeeRef = ReflectionUtils.GetTypeName(typeof (EmployeeReference), FormatterAssemblyStyle.Simple);
string json = @"{
""$id"": ""1"",
@@ -128,19 +132,19 @@ public void DeserializeTypeName()
}";
object employee = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects
- });
+ {
+ TypeNameHandling = TypeNameHandling.Objects
+ });
- CustomAssert.IsInstanceOfType(typeof(EmployeeReference), employee);
- Assert.AreEqual("Name!", ((EmployeeReference)employee).Name);
+ CustomAssert.IsInstanceOfType(typeof (EmployeeReference), employee);
+ Assert.AreEqual("Name!", ((EmployeeReference) employee).Name);
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
[Test]
public void DeserializeTypeNameFromGacAssembly()
{
- string cookieRef = ReflectionUtils.GetTypeName(typeof(Cookie), FormatterAssemblyStyle.Simple);
+ string cookieRef = ReflectionUtils.GetTypeName(typeof (Cookie), FormatterAssemblyStyle.Simple);
string json = @"{
""$id"": ""1"",
@@ -148,19 +152,19 @@ public void DeserializeTypeNameFromGacAssembly()
}";
object cookie = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects
- });
+ {
+ TypeNameHandling = TypeNameHandling.Objects
+ });
- CustomAssert.IsInstanceOfType(typeof(Cookie), cookie);
+ CustomAssert.IsInstanceOfType(typeof (Cookie), cookie);
}
#endif
[Test]
public void SerializeGenericObjectListWithTypeName()
{
- string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
- string personRef = typeof(Person).AssemblyQualifiedName;
+ string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
+ string personRef = typeof (Person).AssemblyQualifiedName;
List<object> values = new List<object>
{
@@ -180,10 +184,10 @@ public void SerializeGenericObjectListWithTypeName()
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
- });
+ {
+ TypeNameHandling = TypeNameHandling.Objects,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
+ });
Assert.AreEqual(@"[
{
@@ -211,8 +215,8 @@ public void SerializeGenericObjectListWithTypeName()
[Test]
public void DeserializeGenericObjectListWithTypeName()
{
- string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
- string personRef = typeof(Person).AssemblyQualifiedName;
+ string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
+ string personRef = typeof (Person).AssemblyQualifiedName;
string json = @"[
{
@@ -236,16 +240,16 @@ public void DeserializeGenericObjectListWithTypeName()
-2147483648
]";
- List<object> values = (List<object>)JsonConvert.DeserializeObject(json, typeof(List<object>), new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
- });
+ List<object> values = (List<object>) JsonConvert.DeserializeObject(json, typeof (List<object>), new JsonSerializerSettings
+ {
+ TypeNameHandling = TypeNameHandling.Objects,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
+ });
Assert.AreEqual(4, values.Count);
- EmployeeReference e = (EmployeeReference)values[0];
- Person p = (Person)values[1];
+ EmployeeReference e = (EmployeeReference) values[0];
+ Person p = (Person) values[1];
Assert.AreEqual("Bob", e.Name);
Assert.AreEqual("Frank", e.Manager.Name);
@@ -255,14 +259,14 @@ public void DeserializeGenericObjectListWithTypeName()
Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.LastModified);
Assert.AreEqual("String!", values[2]);
- Assert.AreEqual((long)int.MinValue, values[3]);
+ Assert.AreEqual((long) int.MinValue, values[3]);
}
[Test]
public void DeserializeWithBadTypeName()
{
- string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
- string personRef = typeof(Person).AssemblyQualifiedName;
+ string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
+ string personRef = typeof (Person).AssemblyQualifiedName;
string json = @"{
""$id"": ""1"",
@@ -273,11 +277,11 @@ public void DeserializeWithBadTypeName()
try
{
- JsonConvert.DeserializeObject(json, typeof(Person), new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
- });
+ JsonConvert.DeserializeObject(json, typeof (Person), new JsonSerializerSettings
+ {
+ TypeNameHandling = TypeNameHandling.Objects,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
+ });
}
catch (JsonSerializationException ex)
{
@@ -288,7 +292,7 @@ public void DeserializeWithBadTypeName()
[Test]
public void DeserializeTypeNameWithNoTypeNameHandling()
{
- string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
+ string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
string json = @"{
""$id"": ""1"",
@@ -297,7 +301,7 @@ public void DeserializeTypeNameWithNoTypeNameHandling()
""Manager"": null
}";
- JObject o = (JObject)JsonConvert.DeserializeObject(json);
+ JObject o = (JObject) JsonConvert.DeserializeObject(json);
Assert.AreEqual(@"{
""Name"": ""Name!"",
@@ -318,12 +322,12 @@ public void DeserializeTypeNameOnly()
ExceptionAssert.Throws<JsonSerializationException>(
"Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.",
() =>
- {
- JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
- TypeNameHandling = TypeNameHandling.Objects
+ JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
+ {
+ TypeNameHandling = TypeNameHandling.Objects
+ });
});
- });
}
public interface ICorrelatedMessage
@@ -338,6 +342,7 @@ public SendHttpRequest()
RequestEncoding = "UTF-8";
Method = "GET";
}
+
public string Method { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Url { get; set; }
@@ -352,7 +357,7 @@ public SendHttpRequest()
[Test]
public void DeserializeGenericTypeName()
{
- string typeName = typeof(SendHttpRequest).AssemblyQualifiedName;
+ string typeName = typeof (SendHttpRequest).AssemblyQualifiedName;
string json = @"{
""$type"": """ + typeName + @""",
@@ -368,14 +373,14 @@ public void DeserializeGenericTypeName()
}";
ICorrelatedMessage message = JsonConvert.DeserializeObject<ICorrelatedMessage>(json, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
- });
+ {
+ TypeNameHandling = TypeNameHandling.Objects,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
+ });
- CustomAssert.IsInstanceOfType(typeof(SendHttpRequest), message);
+ CustomAssert.IsInstanceOfType(typeof (SendHttpRequest), message);
- SendHttpRequest request = (SendHttpRequest)message;
+ SendHttpRequest request = (SendHttpRequest) message;
Assert.AreEqual("xyz", request.CorrelationId);
Assert.AreEqual(2, request.RequestData.Count);
Assert.AreEqual("siedemnaście", request.RequestData["Id"]);
@@ -384,22 +389,22 @@ public void DeserializeGenericTypeName()
[Test]
public void SerializeObjectWithMultipleGenericLists()
{
- string containerTypeName = typeof(Container).AssemblyQualifiedName;
- string productListTypeName = typeof(List<Product>).AssemblyQualifiedName;
+ string containerTypeName = typeof (Container).AssemblyQualifiedName;
+ string productListTypeName = typeof (List<Product>).AssemblyQualifiedName;
Container container = new Container
- {
- In = new List<Product>(),
- Out = new List<Product>()
- };
+ {
+ In = new List<Product>(),
+ Out = new List<Product>()
+ };
string json = JsonConvert.SerializeObject(container, Formatting.Indented,
- new JsonSerializerSettings
- {
- NullValueHandling = NullValueHandling.Ignore,
- TypeNameHandling = TypeNameHandling.All,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
- });
+ new JsonSerializerSettings
+ {
+ NullValueHandling = NullValueHandling.Ignore,
+ TypeNameHandling = TypeNameHandling.All,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
+ });
Assert.AreEqual(@"{
""$type"": """ + containerTypeName + @""",
@@ -417,6 +422,7 @@ public void SerializeObjectWithMultipleGenericLists()
public class TypeNameProperty
{
public string Name { get; set; }
+
[JsonProperty(TypeNameHandling = TypeNameHandling.All)]
public object Value { get; set; }
}
@@ -424,16 +430,16 @@ public class TypeNameProperty
[Test]
public void WriteObjectTypeNameForProperty()
{
- string typeNamePropertyRef = ReflectionUtils.GetTypeName(typeof(TypeNameProperty), FormatterAssemblyStyle.Simple);
+ string typeNamePropertyRef = ReflectionUtils.GetTypeName(typeof (TypeNameProperty), FormatterAssemblyStyle.Simple);
TypeNameProperty typeNameProperty = new TypeNameProperty
- {
- Name = "Name!",
- Value = new TypeNameProperty
{
- Name = "Nested!"
- }
- };
+ Name = "Name!",
+ Value = new TypeNameProperty
+ {
+ Name = "Nested!"
+ }
+ };
string json = JsonConvert.SerializeObject(typeNameProperty, Formatting.Indented);
@@ -448,9 +454,9 @@ public void WriteObjectTypeNameForProperty()
TypeNameProperty deserialized = JsonConvert.DeserializeObject<TypeNameProperty>(json);
Assert.AreEqual("Name!", deserialized.Name);
- CustomAssert.IsInstanceOfType(typeof(TypeNameProperty), deserialized.Value);
+ CustomAssert.IsInstanceOfType(typeof (TypeNameProperty), deserialized.Value);
- TypeNameProperty nested = (TypeNameProperty)deserialized.Value;
+ TypeNameProperty nested = (TypeNameProperty) deserialized.Value;
Assert.AreEqual("Nested!", nested.Name);
Assert.AreEqual(null, nested.Value);
}
@@ -458,13 +464,13 @@ public void WriteObjectTypeNameForProperty()
[Test]
public void WriteListTypeNameForProperty()
{
- string listRef = ReflectionUtils.GetTypeName(typeof(List<int>), FormatterAssemblyStyle.Simple);
+ string listRef = ReflectionUtils.GetTypeName(typeof (List<int>), FormatterAssemblyStyle.Simple);
TypeNameProperty typeNameProperty = new TypeNameProperty
- {
- Name = "Name!",
- Value = new List<int> { 1, 2, 3, 4, 5 }
- };
+ {
+ Name = "Name!",
+ Value = new List<int> {1, 2, 3, 4, 5}
+ };
string json = JsonConvert.SerializeObject(typeNameProperty, Formatting.Indented);
@@ -484,9 +490,9 @@ public void WriteListTypeNameForProperty()
TypeNameProperty deserialized = JsonConvert.DeserializeObject<TypeNameProperty>(json);
Assert.AreEqual("Name!", deserialized.Name);
- CustomAssert.IsInstanceOfType(typeof(List<int>), deserialized.Value);
+ CustomAssert.IsInstanceOfType(typeof (List<int>), deserialized.Value);
- List<int> nested = (List<int>)deserialized.Value;
+ List<int> nested = (List<int>) deserialized.Value;
Assert.AreEqual(5, nested.Count);
Assert.AreEqual(1, nested[0]);
Assert.AreEqual(2, nested[1]);
@@ -505,14 +511,14 @@ public void DeserializeUsingCustomBinder()
}";
object p = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Objects,
- Binder = new CustomSerializationBinder()
- });
+ {
+ TypeNameHandling = TypeNameHandling.Objects,
+ Binder = new CustomSerializationBinder()
+ });
- CustomAssert.IsInstanceOfType(typeof(Person), p);
+ CustomAssert.IsInstanceOfType(typeof (Person), p);
- Person person = (Person)p;
+ Person person = (Person) p;
Assert.AreEqual("Name!", person.Name);
}
@@ -521,7 +527,7 @@ public class CustomSerializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
- return typeof(Person);
+ return typeof (Person);
}
}
@@ -546,10 +552,10 @@ public void SerializeUsingCustomBinder()
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Auto,
- Binder = binder
- });
+ {
+ TypeNameHandling = TypeNameHandling.Auto,
+ Binder = binder
+ });
//[
// {
@@ -579,17 +585,17 @@ public void SerializeUsingCustomBinder()
]", json);
IList<object> newValues = JsonConvert.DeserializeObject<IList<object>>(json, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.Auto,
- Binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests")
- });
+ {
+ TypeNameHandling = TypeNameHandling.Auto,
+ Binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests")
+ });
- CustomAssert.IsInstanceOfType(typeof(Customer), newValues[0]);
- Customer customer = (Customer)newValues[0];
+ CustomAssert.IsInstanceOfType(typeof (Customer), newValues[0]);
+ Customer customer = (Customer) newValues[0];
Assert.AreEqual("Caroline Customer", customer.Name);
- CustomAssert.IsInstanceOfType(typeof(Purchase), newValues[1]);
- Purchase purchase = (Purchase)newValues[1];
+ CustomAssert.IsInstanceOfType(typeof (Purchase), newValues[1]);
+ Purchase purchase = (Purchase) newValues[1];
Assert.AreEqual("Elbow Grease", purchase.ProductName);
}
@@ -640,9 +646,9 @@ public void CollectionWithAbstractItems()
string json = sw.ToString();
- string contentSubClassRef = ReflectionUtils.GetTypeName(typeof(ContentSubClass), FormatterAssemblyStyle.Simple);
- string dictionaryRef = ReflectionUtils.GetTypeName(typeof(Dictionary<int, IList<ContentBaseClass>>), FormatterAssemblyStyle.Simple);
- string listRef = ReflectionUtils.GetTypeName(typeof(List<ContentBaseClass>), FormatterAssemblyStyle.Simple);
+ string contentSubClassRef = ReflectionUtils.GetTypeName(typeof (ContentSubClass), FormatterAssemblyStyle.Simple);
+ string dictionaryRef = ReflectionUtils.GetTypeName(typeof (Dictionary<int, IList<ContentBaseClass>>), FormatterAssemblyStyle.Simple);
+ string listRef = ReflectionUtils.GetTypeName(typeof (List<ContentBaseClass>), FormatterAssemblyStyle.Simple);
string expected = @"{
""TestMember"": {
@@ -680,15 +686,15 @@ public void CollectionWithAbstractItems()
}
Assert.IsNotNull(anotherTestObject);
- CustomAssert.IsInstanceOfType(typeof(ContentSubClass), anotherTestObject.TestMember);
- CustomAssert.IsInstanceOfType(typeof(Dictionary<int, IList<ContentBaseClass>>), anotherTestObject.AnotherTestMember);
+ CustomAssert.IsInstanceOfType(typeof (ContentSubClass), anotherTestObject.TestMember);
+ CustomAssert.IsInstanceOfType(typeof (Dictionary<int, IList<ContentBaseClass>>), anotherTestObject.AnotherTestMember);
Assert.AreEqual(1, anotherTestObject.AnotherTestMember.Count);
IList<ContentBaseClass> list = anotherTestObject.AnotherTestMember[1];
- CustomAssert.IsInstanceOfType(typeof(List<ContentBaseClass>), list);
+ CustomAssert.IsInstanceOfType(typeof (List<ContentBaseClass>), list);
Assert.AreEqual(1, list.Count);
- CustomAssert.IsInstanceOfType(typeof(ContentSubClass), list[0]);
+ CustomAssert.IsInstanceOfType(typeof (ContentSubClass), list[0]);
}
[Test]
@@ -697,10 +703,10 @@ public void WriteObjectTypeNameForPropertyDemo()
Message message = new Message();
message.Address = "http://www.google.com";
message.Body = new SearchDetails
- {
- Query = "Json.NET",
- Language = "en-us"
- };
+ {
+ Query = "Json.NET",
+ Language = "en-us"
+ };
string json = JsonConvert.SerializeObject(message, Formatting.Indented);
// {
@@ -714,7 +720,7 @@ public void WriteObjectTypeNameForPropertyDemo()
Message deserialized = JsonConvert.DeserializeObject<Message>(json);
- SearchDetails searchDetails = (SearchDetails)deserialized.Body;
+ SearchDetails searchDetails = (SearchDetails) deserialized.Body;
// Json.NET
}
@@ -730,23 +736,24 @@ public void GenericDictionaryObject()
{
Dictionary<string, object> collection = new Dictionary<string, object>()
{
- {"First", new UrlStatus{ Status = 404, Url = @"http://www.bing.com"}},
- {"Second", new UrlStatus{Status = 400, Url = @"http://www.google.com"}},
- {"List", new List<UrlStatus>
- {
- new UrlStatus {Status = 300, Url = @"http://www.yahoo.com"},
- new UrlStatus {Status = 200, Url = @"http://www.askjeeves.com"}
+ {"First", new UrlStatus {Status = 404, Url = @"http://www.bing.com"}},
+ {"Second", new UrlStatus {Status = 400, Url = @"http://www.google.com"}},
+ {
+ "List", new List<UrlStatus>
+ {
+ new UrlStatus {Status = 300, Url = @"http://www.yahoo.com"},
+ new UrlStatus {Status = 200, Url = @"http://www.askjeeves.com"}
+ }
}
- }
};
string json = JsonConvert.SerializeObject(collection, Formatting.Indented, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.All,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
- });
+ {
+ TypeNameHandling = TypeNameHandling.All,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
+ });
- string urlStatusTypeName = ReflectionUtils.GetTypeName(typeof(UrlStatus), FormatterAssemblyStyle.Simple);
+ string urlStatusTypeName = ReflectionUtils.GetTypeName(typeof (UrlStatus), FormatterAssemblyStyle.Simple);
Assert.AreEqual(@"{
""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
@@ -778,18 +785,18 @@ public void GenericDictionaryObject()
}", json);
object c = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.All,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
- });
+ {
+ TypeNameHandling = TypeNameHandling.All,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
+ });
- CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c);
+ CustomAssert.IsInstanceOfType(typeof (Dictionary<string, object>), c);
- Dictionary<string, object> newCollection = (Dictionary<string, object>)c;
+ Dictionary<string, object> newCollection = (Dictionary<string, object>) c;
Assert.AreEqual(3, newCollection.Count);
- Assert.AreEqual(@"http://www.bing.com", ((UrlStatus)newCollection["First"]).Url);
+ Assert.AreEqual(@"http://www.bing.com", ((UrlStatus) newCollection["First"]).Url);
- List<UrlStatus> statues = (List<UrlStatus>)newCollection["List"];
+ List<UrlStatus> statues = (List<UrlStatus>) newCollection["List"];
Assert.AreEqual(2, statues.Count);
}
@@ -797,11 +804,11 @@ public void GenericDictionaryObject()
[Test]
public void SerializingIEnumerableOfTShouldRetainGenericTypeInfo()
{
- string productClassRef = ReflectionUtils.GetTypeName(typeof(Product[]), FormatterAssemblyStyle.Simple);
+ string productClassRef = ReflectionUtils.GetTypeName(typeof (Product[]), FormatterAssemblyStyle.Simple);
CustomEnumerable<Product> products = new CustomEnumerable<Product>();
- string json = JsonConvert.SerializeObject(products, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
+ string json = JsonConvert.SerializeObject(products, Formatting.Indented, new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All});
Assert.AreEqual(@"{
""$type"": """ + productClassRef + @""",
@@ -872,8 +879,8 @@ public void ByteArrays()
{
Car testerObject = new Car();
testerObject.Year = new DateTime(2000, 10, 5, 1, 1, 1, DateTimeKind.Utc);
- byte[] data = new byte[] { 75, 65, 82, 73, 82, 65 };
- testerObject.Objects = new object[] { data, "prueba" };
+ byte[] data = new byte[] {75, 65, 82, 73, 82, 65};
+ testerObject.Objects = new object[] {data, "prueba"};
JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
jsonSettings.NullValueHandling = NullValueHandling.Ignore;
@@ -881,7 +888,7 @@ public void ByteArrays()
string output = JsonConvert.SerializeObject(testerObject, Formatting.Indented, jsonSettings);
- string carClassRef = ReflectionUtils.GetTypeName(typeof(Car), FormatterAssemblyStyle.Simple);
+ string carClassRef = ReflectionUtils.GetTypeName(typeof (Car), FormatterAssemblyStyle.Simple);
Assert.AreEqual(output, @"{
""$type"": """ + carClassRef + @""",
@@ -903,7 +910,7 @@ public void ByteArrays()
Assert.IsTrue(obj.Objects[0] is byte[]);
- byte[] d = (byte[])obj.Objects[0];
+ byte[] d = (byte[]) obj.Objects[0];
CollectionAssert.AreEquivalent(data, d);
}
@@ -915,9 +922,9 @@ public void ISerializableTypeNameHandlingTest()
IExample e = new Example("Rob");
SerializableWrapper w = new SerializableWrapper
- {
- Content = e
- };
+ {
+ Content = e
+ };
//Test Binary Serialization Round Trip
//This will work find because the Binary Formatter serializes type names
@@ -961,23 +968,23 @@ private void TestJsonSerializationRoundTrip(SerializableWrapper e, TypeNameHandl
public void SerializationBinderWithFullName()
{
Message message = new Message
- {
- Address = "jamesnk@testtown.com",
- Body = new Version(1, 2, 3, 4)
- };
+ {
+ Address = "jamesnk@testtown.com",
+ Body = new Version(1, 2, 3, 4)
+ };
string json = JsonConvert.SerializeObject(message, Formatting.Indented, new JsonSerializerSettings
- {
- TypeNameHandling = TypeNameHandling.All,
- TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
- Binder = new MetroBinder(),
- ContractResolver = new DefaultContractResolver
{
+ TypeNameHandling = TypeNameHandling.All,
+ TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
+ Binder = new MetroBinder(),
+ ContractResolver = new DefaultContractResolver
+ {
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
IgnoreSerializableAttribute = true
#endif
- }
- });
+ }
+ });
Assert.AreEqual(@"{
""$type"": "":::MESSAGE:::, AssemblyName"",
@@ -1037,10 +1044,10 @@ public void TypeNameComponentList()
TypeNameList<object> l = new TypeNameList<object>();
l.Add(c1);
l.Add(new Employee
- {
- BirthDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
- Department = "Department!"
- });
+ {
+ BirthDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
+ Department = "Department!"
+ });
l.Add("String!");
l.Add(long.MaxValue);
@@ -1065,17 +1072,17 @@ public void TypeNameComponentList()
TypeNameList<object> l2 = JsonConvert.DeserializeObject<TypeNameList<object>>(json);
Assert.AreEqual(4, l2.Count);
- CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), l2[0]);
- CustomAssert.IsInstanceOfType(typeof(Employee), l2[1]);
- CustomAssert.IsInstanceOfType(typeof(string), l2[2]);
- CustomAssert.IsInstanceOfType(typeof(long), l2[3]);
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), l2[0]);
+ CustomAssert.IsInstanceOfType(typeof (Employee), l2[1]);
+ CustomAssert.IsInstanceOfType(typeof (string), l2[2]);
+ CustomAssert.IsInstanceOfType(typeof (long), l2[3]);
}
[Test]
public void TypeNameDictionary()
{
TypeNameDictionary<object> l = new TypeNameDictionary<object>();
- l.Add("First", new TestComponentSimple { MyProperty = 1 });
+ l.Add("First", new TestComponentSimple {MyProperty = 1});
l.Add("Second", "String!");
l.Add("Third", long.MaxValue);
@@ -1092,10 +1099,10 @@ public void TypeNameDictionary()
TypeNameDictionary<object> l2 = JsonConvert.DeserializeObject<TypeNameDictionary<object>>(json);
Assert.AreEqual(3, l2.Count);
- CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), l2["First"]);
- Assert.AreEqual(1, ((TestComponentSimple)l2["First"]).MyProperty);
- CustomAssert.IsInstanceOfType(typeof(string), l2["Second"]);
- CustomAssert.IsInstanceOfType(typeof(long), l2["Third"]);
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), l2["First"]);
+ Assert.AreEqual(1, ((TestComponentSimple) l2["First"]).MyProperty);
+ CustomAssert.IsInstanceOfType(typeof (string), l2["Second"]);
+ CustomAssert.IsInstanceOfType(typeof (long), l2["Third"]);
}
[Test]
@@ -1103,9 +1110,9 @@ public void TypeNameObjectItems()
{
TypeNameObject o1 = new TypeNameObject();
- o1.Object1 = new TestComponentSimple { MyProperty = 1 };
+ o1.Object1 = new TestComponentSimple {MyProperty = 1};
o1.Object2 = 123;
- o1.ObjectNotHandled = new TestComponentSimple { MyProperty = int.MaxValue };
+ o1.ObjectNotHandled = new TestComponentSimple {MyProperty = int.MaxValue};
o1.String = "String!";
o1.Integer = int.MaxValue;
@@ -1127,14 +1134,327 @@ public void TypeNameObjectItems()
TypeNameObject o2 = JsonConvert.DeserializeObject<TypeNameObject>(json);
Assert.IsNotNull(o2);
- CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), o2.Object1);
- Assert.AreEqual(1, ((TestComponentSimple)o2.Object1).MyProperty);
- CustomAssert.IsInstanceOfType(typeof(long), o2.Object2);
- CustomAssert.IsInstanceOfType(typeof(JObject), o2.ObjectNotHandled);
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), o2.Object1);
+ Assert.AreEqual(1, ((TestComponentSimple) o2.Object1).MyProperty);
+ CustomAssert.IsInstanceOfType(typeof (long), o2.Object2);
+ CustomAssert.IsInstanceOfType(typeof (JObject), o2.ObjectNotHandled);
Assert.AreEqual(@"{
""MyProperty"": 2147483647
}", o2.ObjectNotHandled.ToString());
}
+
+ [Test]
+ public void PropertyItemTypeNameHandling()
+ {
+ PropertyItemTypeNameHandling c1 = new PropertyItemTypeNameHandling();
+ c1.Data = new List<object>
+ {
+ 1,
+ "two",
+ new TestComponentSimple {MyProperty = 1}
+ };
+
+ string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
+ Assert.AreEqual(@"{
+ ""Data"": [
+ 1,
+ ""two"",
+ {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
+ ""MyProperty"": 1
+ }
+ ]
+}", json);
+
+ PropertyItemTypeNameHandling c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandling>(json);
+ Assert.AreEqual(3, c2.Data.Count);
+
+ CustomAssert.IsInstanceOfType(typeof (long), c2.Data[0]);
+ CustomAssert.IsInstanceOfType(typeof (string), c2.Data[1]);
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data[2]);
+ TestComponentSimple c = (TestComponentSimple) c2.Data[2];
+ Assert.AreEqual(1, c.MyProperty);
+ }
+
+ [Test]
+ public void PropertyItemTypeNameHandlingNestedCollections()
+ {
+ PropertyItemTypeNameHandling c1 = new PropertyItemTypeNameHandling
+ {
+ Data = new List<object>
+ {
+ new TestComponentSimple {MyProperty = 1},
+ new List<object>
+ {
+ new List<object>
+ {
+ new List<object>()
+ }
+ }
+ }
+ };
+
+ string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
+ Assert.AreEqual(@"{
+ ""Data"": [
+ {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
+ ""MyProperty"": 1
+ },
+ {
+ ""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
+ ""$values"": [
+ [
+ []
+ ]
+ ]
+ }
+ ]
+}", json);
+
+ PropertyItemTypeNameHandling c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandling>(json);
+ Assert.AreEqual(2, c2.Data.Count);
+
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data[0]);
+ CustomAssert.IsInstanceOfType(typeof (List<object>), c2.Data[1]);
+ List<object> c = (List<object>) c2.Data[1];
+ CustomAssert.IsInstanceOfType(typeof (JArray), c[0]);
+
+ json = @"{
+ ""Data"": [
+ {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.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"",
+ ""MyProperty"": 1
+ }
+ ]
+ }
+ ]
+}";
+
+ c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandling>(json);
+ Assert.AreEqual(2, c2.Data.Count);
+
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data[0]);
+ CustomAssert.IsInstanceOfType(typeof (List<object>), c2.Data[1]);
+ c = (List<object>) c2.Data[1];
+ CustomAssert.IsInstanceOfType(typeof (JObject), c[0]);
+ JObject o = (JObject) c[0];
+ Assert.AreEqual(1, (int) o["MyProperty"]);
+ }
+
+ [Test]
+ public void PropertyItemTypeNameHandlingNestedDictionaries()
+ {
+ PropertyItemTypeNameHandlingDictionary c1 = new PropertyItemTypeNameHandlingDictionary()
+ {
+ Data = new Dictionary<string, object>
+ {
+ {
+ "one", new TestComponentSimple {MyProperty = 1}
+ },
+ {
+ "two", new Dictionary<string, object>
+ {
+ {
+ "one", new Dictionary<string, object>
+ {
+ {"one", 1}
+ }
+ }
+ }
+ }
+ }
+ };
+
+ string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
+ Assert.AreEqual(@"{
+ ""Data"": {
+ ""one"": {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
+ ""MyProperty"": 1
+ },
+ ""two"": {
+ ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
+ ""one"": {
+ ""one"": 1
+ }
+ }
+ }
+}", json);
+
+ PropertyItemTypeNameHandlingDictionary c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDictionary>(json);
+ Assert.AreEqual(2, c2.Data.Count);
+
+ CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data["one"]);
+ CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c2.Data["two"]);
+ Dictionary<string, object> c = (Dictionary<string, object>)c2.Data["two"];
+ CustomAssert.IsInstanceOfType(typeof (JObject), c["one"]);
+
+ json = @"{
+ ""Data"": {
+ ""one"": {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.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"",
+ ""MyProperty"": 1
+ }
+ }
+ }
+}";
+
+ c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDictionary>(json);
+ Assert.AreEqual(2, c2.Data.Count);
+
+ CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), c2.Data["one"]);
+ CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c2.Data["two"]);
+ c = (Dictionary<string, object>)c2.Data["two"];
+ CustomAssert.IsInstanceOfType(typeof(JObject), c["one"]);
+
+ JObject o = (JObject) c["one"];
+ Assert.AreEqual(1, (int) o["MyProperty"]);
+ }
+
+ [Test]
+ public void PropertyItemTypeNameHandlingObject()
+ {
+ PropertyItemTypeNameHandlingObject o1 = new PropertyItemTypeNameHandlingObject
+ {
+ Data = new TypeNameHandlingTestObject
+ {
+ Prop1 = new List<object>
+ {
+ new TestComponentSimple
+ {
+ MyProperty = 1
+ }
+ },
+ Prop2 = new TestComponentSimple
+ {
+ MyProperty = 1
+ },
+ Prop3 = 3,
+ Prop4 = new JObject()
+ }
+ };
+
+ string json = JsonConvert.SerializeObject(o1, Formatting.Indented);
+ Assert.AreEqual(@"{
+ ""Data"": {
+ ""Prop1"": {
+ ""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
+ ""$values"": [
+ {
+ ""MyProperty"": 1
+ }
+ ]
+ },
+ ""Prop2"": {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
+ ""MyProperty"": 1
+ },
+ ""Prop3"": 3,
+ ""Prop4"": {}
+ }
+}", json);
+
+ PropertyItemTypeNameHandlingObject o2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingObject>(json);
+ Assert.IsNotNull(o2);
+ Assert.IsNotNull(o2.Data);
+
+ CustomAssert.IsInstanceOfType(typeof(List<object>), o2.Data.Prop1);
+ CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), o2.Data.Prop2);
+ CustomAssert.IsInstanceOfType(typeof(long), o2.Data.Prop3);
+ CustomAssert.IsInstanceOfType(typeof(JObject), o2.Data.Prop4);
+
+ List<object> o = (List<object>)o2.Data.Prop1;
+ JObject j = (JObject)o[0];
+ Assert.AreEqual(1, (int)j["MyProperty"]);
+ }
+
+#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
+ [Test]
+ public void PropertyItemTypeNameHandlingDynamic()
+ {
+ PropertyItemTypeNameHandlingDynamic d1 = new PropertyItemTypeNameHandlingDynamic();
+
+ dynamic data = new DynamicDictionary();
+ data.one = new TestComponentSimple
+ {
+ MyProperty = 1
+ };
+
+ dynamic data2 = new DynamicDictionary();
+ data2.one = new TestComponentSimple
+ {
+ MyProperty = 2
+ };
+
+ data.two = data2;
+
+ d1.Data = (DynamicDictionary)data;
+
+ string json = JsonConvert.SerializeObject(d1, Formatting.Indented);
+ Assert.AreEqual(@"{
+ ""Data"": {
+ ""one"": {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
+ ""MyProperty"": 1
+ },
+ ""two"": {
+ ""$type"": ""Newtonsoft.Json.Tests.Linq.DynamicDictionary, Newtonsoft.Json.Tests"",
+ ""one"": {
+ ""MyProperty"": 2
+ }
+ }
+ }
+}", json);
+
+ PropertyItemTypeNameHandlingDynamic d2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDynamic>(json);
+ Assert.IsNotNull(d2);
+ Assert.IsNotNull(d2.Data);
+
+ dynamic data3 = d2.Data;
+ TestComponentSimple c = (TestComponentSimple)data3.one;
+ Assert.AreEqual(1, c.MyProperty);
+
+ dynamic data4 = data3.two;
+ JObject o = (JObject)data4.one;
+ Assert.AreEqual(2, (int)o["MyProperty"]);
+
+ json = @"{
+ ""Data"": {
+ ""one"": {
+ ""$type"": ""Newtonsoft.Json.Tests.Serialization.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"",
+ ""MyProperty"": 2
+ }
+ }
+ }
+}";
+
+ d2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDynamic>(json);
+ data3 = d2.Data;
+ data4 = data3.two;
+ o = (JObject)data4.one;
+ Assert.AreEqual(2, (int)o["MyProperty"]);
+ }
+#endif
}
public class Message
@@ -1225,6 +1545,40 @@ public override bool Equals(object obj)
}
#endif
+ public class PropertyItemTypeNameHandlingObject
+ {
+ [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
+ public TypeNameHandlingTestObject Data { get; set; }
+ }
+
+#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
+ public class PropertyItemTypeNameHandlingDynamic
+ {
+ [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
+ public DynamicDictionary Data { get; set; }
+ }
+#endif
+
+ public class TypeNameHandlingTestObject
+ {
+ public object Prop1 { get; set; }
+ public object Prop2 { get; set; }
+ public object Prop3 { get; set; }
+ public object Prop4 { get; set; }
+ }
+
+ public class PropertyItemTypeNameHandlingDictionary
+ {
+ [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
+ public IDictionary<string, object> Data { get; set; }
+ }
+
+ public class PropertyItemTypeNameHandling
+ {
+ [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
+ public IList<object> Data { get; set; }
+ }
+
[JsonArray(ItemTypeNameHandling = TypeNameHandling.All)]
public class TypeNameList<T> : List<T>
{
View
16 Src/Newtonsoft.Json/Bson/BsonWriter.cs
@@ -105,7 +105,7 @@ protected override void WriteEnd(JsonToken token)
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
- throw new JsonWriterException("Cannot write JSON comment as BSON.");
+ throw JsonWriterException.Create(this, "Cannot write JSON comment as BSON.", null);
}
/// <summary>
@@ -114,7 +114,7 @@ public override void WriteComment(string text)
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
- throw new JsonWriterException("Cannot write JSON constructor as BSON.");
+ throw JsonWriterException.Create(this, "Cannot write JSON constructor as BSON.", null);
}
/// <summary>
@@ -123,7 +123,7 @@ public override void WriteStartConstructor(string name)
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
{
- throw new JsonWriterException("Cannot write raw JSON as BSON.");
+ throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
/// <summary>
@@ -132,7 +132,7 @@ public override void WriteRaw(string json)
/// <param name="json">The raw JSON to write.</param>
public override void WriteRawValue(string json)
{
- throw new JsonWriterException("Cannot write raw JSON as BSON.");
+ throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
/// <summary>
@@ -210,7 +210,7 @@ internal void AddToken(BsonToken token)
else
{
if (token.Type != BsonType.Object && token.Type != BsonType.Array)
- throw new JsonWriterException("Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type));
+ throw JsonWriterException.Create(this, "Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type), null);
_parent = token;
_root = token;
@@ -268,7 +268,7 @@ public override void WriteValue(int value)
public override void WriteValue(uint value)
{
if (value > int.MaxValue)
- throw new JsonWriterException("Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.");
+ throw JsonWriterException.Create(this, "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.", null);
base.WriteValue(value);
AddValue(value, BsonType.Integer);
@@ -292,7 +292,7 @@ public override void WriteValue(long value)
public override void WriteValue(ulong value)
{
if (value > long.MaxValue)
- throw new JsonWriterException("Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.");
+ throw JsonWriterException.Create(this, "Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.", null);
base.WriteValue(value);
AddValue(value, BsonType.Long);
@@ -470,7 +470,7 @@ public void WriteObjectId(byte[] value)
ValidationUtils.ArgumentNotNull(value, "value");
if (value.Length != 12)
- throw new ArgumentException("An object id must be 12 bytes", "value");
+ throw JsonWriterException.Create(this, "An object id must be 12 bytes", null);
// hack to update the writer state
AutoComplete(JsonToken.Undefined);
View
2 Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs
@@ -23,7 +23,7 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
-#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
+#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE || MONOTOUCH || MONODROID)
using System;
using System.Collections.Generic;
View
19 Src/Newtonsoft.Json/JsonException.cs
@@ -25,8 +25,10 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Runtime.Serialization;
using System.Text;
+using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
@@ -79,5 +81,22 @@ public JsonException(SerializationInfo info, StreamingContext context)
{
}
#endif
+
+ internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string path, string message)
+ {
+ message = message.Trim();
+
+ if (!message.EndsWith("."))
+ message += ".";
+
+ message += " Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
+
+ if (lineInfo != null && lineInfo.HasLineInfo())
+ message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
+
+ message += ".";
+
+ return message;
+ }
}
}
View
43 Src/Newtonsoft.Json/JsonPropertyAttribute.cs
@@ -43,12 +43,15 @@ public sealed class JsonPropertyAttribute : Attribute
internal bool? _isReference;
internal int? _order;
internal Required? _required;
+ internal bool? _itemIsReference;
+ internal ReferenceLoopHandling? _itemReferenceLoopHandling;
+ internal TypeNameHandling? _itemTypeNameHandling;
- ///// <summary>
- ///// Gets the collection's items converter.
- ///// </summary>
- ///// <value>The collection's items converter.</value>
- //public Type ItemConverterType { get; set; }
+ /// <summary>
+ /// Gets or sets the converter used when serializing the property's collection items.
+ /// </summary>
+ /// <value>The collection's items converter.</value>
+ public Type ItemConverterType { get; set; }
/// <summary>
/// Gets or sets the null value handling used when serializing this property.
@@ -139,6 +142,36 @@ public Required Required
public string PropertyName { get; set; }
/// <summary>
+ /// Gets or sets the the reference loop handling used when serializing the property's collection items.
+ /// </summary>
+ /// <value>The collection's items reference loop handling.</value>
+ public ReferenceLoopHandling ItemReferenceLoopHandling
+ {
+ get { return _itemReferenceLoopHandling ?? default(ReferenceLoopHandling); }
+ set { _itemReferenceLoopHandling = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the the type name handling used when serializing the property's collection items.
+ /// </summary>
+ /// <value>The collection's items type name handling.</value>
+ public TypeNameHandling ItemTypeNameHandling
+ {
+ get { return _itemTypeNameHandling ?? default(TypeNameHandling); }
+ set { _itemTypeNameHandling = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets whether this property's collection items are serialized as a reference.
+ /// </summary>
+ /// <value>Whether this property's collection items are serialized as a reference.</value>
+ public bool ItemIsReference
+ {
+ get { return _itemIsReference ?? default(bool); }
+ set { _itemIsReference = value; }
+ }
+
+ /// <summary>
/// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class.
/// </summary>
public JsonPropertyAttribute()
View
18 Src/Newtonsoft.Json/JsonReaderException.cs
@@ -44,7 +44,6 @@ public class JsonReaderException : JsonException
/// <value>The line number indicating where the error occurred.</value>
public int LineNumber { get; private set; }
-
/// <summary>
/// Gets the line position indicating where the error occurred.
/// </summary>
@@ -136,22 +135,5 @@ internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path,
return new JsonReaderException(message, ex, path, lineNumber, linePosition);
}
-
- internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string path, string message)
- {
- message = message.Trim();
-
- if (!message.EndsWith("."))
- message += ".";
-
- message += " Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
-
- if (lineInfo != null && lineInfo.HasLineInfo())
- message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
-
- message += ".";
-
- return message;
- }
}
}
View
2 Src/Newtonsoft.Json/JsonSerializationException.cs
@@ -92,7 +92,7 @@ internal static JsonSerializationException Create(JsonReader reader, string mess
internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
- message = JsonReaderException.FormatExceptionMessage(lineInfo, path, message);
+ message = FormatExceptionMessage(lineInfo, path, message);
return new JsonSerializationException(message, ex);
}
View
2 Src/Newtonsoft.Json/JsonTextWriter.cs
@@ -194,7 +194,7 @@ protected override void WriteEnd(JsonToken token)
_writer.Write(")");
break;
default:
- throw new JsonWriterException("Invalid JsonToken: " + token);
+ throw JsonWriterException.Create(this, "Invalid JsonToken: " + token, null);
}
}
View
28 Src/Newtonsoft.Json/JsonWriter.cs
@@ -185,7 +185,7 @@ public WriteState WriteState
case State.Start:
return WriteState.Start;
default:
- throw new JsonWriterException("Invalid state: " + _currentState);
+ throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
@@ -482,17 +482,17 @@ internal void WriteToken(JsonReader reader, int initialDepth)
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
- throw new JsonWriterException("Unexpected end when reading date constructor.");
+ throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
if (reader.TokenType != JsonToken.Integer)
- throw new JsonWriterException("Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType);
+ throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);