diff --git a/Src/Newtonsoft.Json.TestConsole/App.config b/Src/Newtonsoft.Json.TestConsole/App.config index 8e156463..5c73fc53 100644 --- a/Src/Newtonsoft.Json.TestConsole/App.config +++ b/Src/Newtonsoft.Json.TestConsole/App.config @@ -1,6 +1,7 @@ - + + - - - + + + \ No newline at end of file diff --git a/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.project.json b/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.project.json index 8a7fd6ef..572bc9ed 100644 --- a/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.project.json +++ b/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.project.json @@ -3,6 +3,6 @@ "net45": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.TestConsole/Program.cs b/Src/Newtonsoft.Json.TestConsole/Program.cs index 994af9f7..c223d819 100644 --- a/Src/Newtonsoft.Json.TestConsole/Program.cs +++ b/Src/Newtonsoft.Json.TestConsole/Program.cs @@ -164,4 +164,4 @@ namespace Newtonsoft.Json.TestConsole Console.WriteLine("Finished. Total seconds: " + sw.Elapsed.TotalSeconds); } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.TestConsole/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.TestConsole/Properties/AssemblyInfo.cs index 0e0a3394..321f5ebf 100644 --- a/Src/Newtonsoft.Json.TestConsole/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.TestConsole/Properties/AssemblyInfo.cs @@ -30,6 +30,7 @@ using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyTitle("Json.NET Test Console")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] @@ -42,9 +43,11 @@ using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. + [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM + [assembly: Guid("bf0cc842-d368-4800-9614-b5abcc736110")] // Version information for an assembly consists of the following four values: @@ -56,5 +59,6 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: + [assembly: AssemblyVersion("7.0.0.0")] -[assembly: AssemblyFileVersion("7.0.2.18802")] +[assembly: AssemblyFileVersion("7.0.2.18802")] \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs index bf740f15..0eb3dbd2 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs @@ -920,7 +920,9 @@ namespace Newtonsoft.Json.Tests.Bson for (int i = 0; i < 100; i++) { if (i > 0) + { largeStringBuilder.Append("-"); + } largeStringBuilder.Append(i.ToString(CultureInfo.InvariantCulture)); } @@ -1606,6 +1608,7 @@ namespace Newtonsoft.Json.Tests.Bson #if !(NET20 || NET35) public bool BindToNameCalled { get; set; } + public override void BindToName(Type serializedType, out string assemblyName, out string typeName) { BindToNameCalled = true; @@ -1677,7 +1680,7 @@ namespace Newtonsoft.Json.Tests.Bson BsonReader reader = new BsonReader(new MemoryStream(bytes)); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read()); - + Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Bytes, reader.TokenType); Assert.AreEqual(typeof(Guid), reader.ValueType); diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs index ebfeed01..ec8c58ca 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs @@ -301,7 +301,9 @@ namespace Newtonsoft.Json.Tests.Bson for (int i = 0; i < 100; i++) { if (i > 0) + { largeStringBuilder.Append("-"); + } largeStringBuilder.Append(i.ToString(CultureInfo.InvariantCulture)); } @@ -483,7 +485,6 @@ namespace Newtonsoft.Json.Tests.Bson // 6D-61-6C-6C-00-02-31-00-07-00-00-00-4D-65-64-69-75-6D- // 00-02-32-00-06-00-00-00-4C-61-72-67-65-00-00-00 - ms.Seek(0, SeekOrigin.Begin); // deserialize product from BSON @@ -493,7 +494,6 @@ namespace Newtonsoft.Json.Tests.Bson Console.WriteLine(deserializedProduct.Name); // Carlos' Spicy Wieners - Assert.AreEqual("Carlos' Spicy Wieners", deserializedProduct.Name); Assert.AreEqual(9.95m, deserializedProduct.Price); Assert.AreEqual(3, deserializedProduct.Sizes.Length); @@ -745,10 +745,7 @@ namespace Newtonsoft.Json.Tests.Bson BsonWriter writer = new BsonWriter(ms); - ExceptionAssert.Throws(() => - { - serializer.Serialize(writer, b); - }, "Error writing Binary value. BSON must start with an Object or Array. Path ''."); + ExceptionAssert.Throws(() => { serializer.Serialize(writer, b); }, "Error writing Binary value. BSON must start with an Object or Array. Path ''."); } public class GuidTestClass diff --git a/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs index a33e6ce9..29cd42dd 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs @@ -43,6 +43,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Converters diff --git a/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs index 41ccfbac..3589c930 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/CustomCreationConverterTests.cs @@ -36,6 +36,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Converters diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs index 3699eb62..cda7decb 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs @@ -590,4 +590,5 @@ namespace Newtonsoft.Json.Tests.Converters } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs index ab3cb8d8..0a22a17d 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs @@ -508,7 +508,7 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual(new System.Data.SqlTypes.SqlDateTime(2015, 11, 28), ds.TestTable[0].DateTimeValue); Assert.AreEqual(System.Data.SqlTypes.SqlDateTime.Null, ds.TestTable[1].DateTimeValue); - + string json2 = JsonConvert.SerializeObject(ds, Formatting.Indented, new SqlDateTimeConverter()); StringAssert.AreEqual(json, json2); @@ -524,20 +524,29 @@ namespace Newtonsoft.Json.Tests.Converters public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value == null || reader.Value == DBNull.Value) + { return System.Data.SqlTypes.SqlDateTime.Null; + } else + { return new System.Data.SqlTypes.SqlDateTime((DateTime)serializer.Deserialize(reader)); + } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (((System.Data.SqlTypes.SqlDateTime)value).IsNull) + { writer.WriteNull(); + } else + { writer.WriteValue(((System.Data.SqlTypes.SqlDateTime)value).Value); + } } } #endif } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs index f422a2a5..a34249e7 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs @@ -300,4 +300,5 @@ namespace Newtonsoft.Json.Tests.Converters } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs index f95413ab..b2588f5d 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/ExpandoObjectConverterTests.cs @@ -40,6 +40,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Converters diff --git a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs index 40062de1..c9b81b5d 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs @@ -256,9 +256,13 @@ namespace Newtonsoft.Json.Tests.Converters // if the current timezone is utc then local already equals utc if (offset == TimeSpan.Zero) + { Assert.AreEqual(json, json2); + } else + { Assert.AreNotEqual(json, json2); + } } #endif diff --git a/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs index b079843b..4bf0501a 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs @@ -227,9 +227,13 @@ namespace Newtonsoft.Json.Tests.Converters { DateTime? d = (DateTime?)value; if (d == null) + { writer.WriteNull(); + } else + { writer.WriteValue(d.Value.Ticks); + } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) diff --git a/Src/Newtonsoft.Json.Tests/Converters/KeyValuePairConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/KeyValuePairConverterTests.cs index 07e6a7fe..47e6f203 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/KeyValuePairConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/KeyValuePairConverterTests.cs @@ -13,6 +13,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Converters @@ -24,7 +25,7 @@ namespace Newtonsoft.Json.Tests.Converters public void SerializeUsingInternalConverter() { DefaultContractResolver contractResolver = new DefaultContractResolver(); - JsonObjectContract contract = (JsonObjectContract) contractResolver.ResolveContract(typeof (KeyValuePair)); + JsonObjectContract contract = (JsonObjectContract)contractResolver.ResolveContract(typeof(KeyValuePair)); Assert.AreEqual(typeof(KeyValuePairConverter), contract.InternalConverter.GetType()); diff --git a/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs index 8a14569e..c4573303 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/ObjectIdConverterTests.cs @@ -36,6 +36,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Converters diff --git a/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs index 9240de41..3bf060d3 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/StringEnumConverterTests.cs @@ -500,7 +500,6 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual(DuplicateNameEnum.foo_bar, o.Value); Assert.AreEqual(DuplicateNameEnum2.FooBar, o.Value2); - }, "Type 'Newtonsoft.Json.Tests.Converters.DuplicateNameEnum' contains two members 'foo_bar' 'and 'FooBar' with the same name 'foo_bar'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using EnumMemberAttribute attribute."); } #endif @@ -512,6 +511,7 @@ namespace Newtonsoft.Json.Tests.Converters { [DataMember] public DuplicateNameEnum Value { get; set; } + [DataMember] public DuplicateNameEnum2 Value2 { get; set; } } @@ -521,10 +521,13 @@ namespace Newtonsoft.Json.Tests.Converters { [EnumMember] first = 0, + [EnumMember] foo_bar = 1, + [EnumMember(Value = "foo_bar")] FooBar = 2, + [EnumMember] foo_bar_NOT_USED = 3 } @@ -534,10 +537,13 @@ namespace Newtonsoft.Json.Tests.Converters { [EnumMember] first = 0, + [EnumMember(Value = "foo_bar")] FooBar = 1, + [EnumMember] foo_bar = 2, + [EnumMember(Value = "TEST")] foo_bar_NOT_USED = 3 } diff --git a/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs index 38393e3c..f75c2797 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/VersionConverterTests.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Converters diff --git a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs index 1ceda7a1..a7a5f942 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs @@ -53,6 +53,7 @@ using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; #if !NET20 using System.Xml.Linq; + #endif namespace Newtonsoft.Json.Tests.Converters @@ -103,7 +104,9 @@ namespace Newtonsoft.Json.Tests.Converters reader.Read(); XmlNodeConverter converter = new XmlNodeConverter(); if (deserializeRootElementName != null) + { converter.DeserializeRootElementName = deserializeRootElementName; + } XmlNode node = (XmlNode)converter.ReadJson(reader, typeof(XmlDocument), null, new JsonSerializer()); @@ -116,7 +119,9 @@ namespace Newtonsoft.Json.Tests.Converters string linqXmlText = d.ToString(SaveOptions.DisableFormatting); if (d.Declaration != null) + { linqXmlText = d.Declaration + linqXmlText; + } Assert.AreEqual(xmlText, linqXmlText); #endif @@ -238,7 +243,7 @@ namespace Newtonsoft.Json.Tests.Converters var result = xmlDocument.FirstChild.ChildNodes.Cast().ToArray(); - var json = JsonConvert.SerializeObject(result, Formatting.Indented); // <--- fails here with the cast message + var json = JsonConvert.SerializeObject(result, Formatting.Indented); // <--- fails here with the cast message StringAssert.AreEqual(@"[ { @@ -275,7 +280,7 @@ namespace Newtonsoft.Json.Tests.Converters var result = xmlDocument.Root.Nodes().ToArray(); - var json = JsonConvert.SerializeObject(result, Formatting.Indented); // <--- fails here with the cast message + var json = JsonConvert.SerializeObject(result, Formatting.Indented); // <--- fails here with the cast message StringAssert.AreEqual(@"[ { @@ -446,10 +451,7 @@ namespace Newtonsoft.Json.Tests.Converters } }"; ExceptionAssert.Throws( - () => - { - JsonConvert.DeserializeXmlNode(json); - }, + () => { JsonConvert.DeserializeXmlNode(json); }, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName. Path 'Email', line 3, position 13."); } @@ -553,7 +555,6 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual(@"{""?xml-stylesheet"":""href=\""classic.xsl\"" type=\""text/xml\""""}", jsonText); - // XmlProcessingInstruction XmlCDataSection cDataSection = doc.CreateCDataSection("true"); @@ -561,7 +562,6 @@ namespace Newtonsoft.Json.Tests.Converters Assert.AreEqual(@"{""#cdata-section"":""true""}", jsonText); - // XmlElement XmlElement element = doc.CreateElement("xs", "Choice", "http://www.w3.org/2001/XMLSchema"); element.SetAttributeNode(doc.CreateAttribute("msdata", "IsDataSet", "urn:schemas-microsoft-com:xml-msdata")); @@ -711,7 +711,10 @@ namespace Newtonsoft.Json.Tests.Converters public class Utf8StringWriter : StringWriter { - public override Encoding Encoding { get { return Encoding.UTF8; } } + public override Encoding Encoding + { + get { return Encoding.UTF8; } + } public Utf8StringWriter(StringBuilder sb) : base(sb) { @@ -1303,7 +1306,7 @@ namespace Newtonsoft.Json.Tests.Converters StringAssert.AreEqual(expected, jsonText); XmlDocument newDoc = (XmlDocument)DeserializeXmlNode(jsonText); - Assert.AreEqual(@"Text", newDoc.InnerXml); + Assert.AreEqual(@"Text", newDoc.InnerXml); } [Test] @@ -1948,7 +1951,9 @@ namespace Newtonsoft.Json.Tests.Converters { XmlDocument doc = (XmlDocument)serializer.Deserialize(reader, typeof(XmlDocument)); if (reader.Read() && reader.TokenType != JsonToken.Comment) + { throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); + } using (XmlWriter writer = XmlWriter.Create(xml)) { doc.Save(writer); @@ -2583,4 +2588,5 @@ namespace Newtonsoft.Json.Tests.Converters #endif } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/DemoTests.cs b/Src/Newtonsoft.Json.Tests/DemoTests.cs index 9d797159..39bbffbd 100644 --- a/Src/Newtonsoft.Json.Tests/DemoTests.cs +++ b/Src/Newtonsoft.Json.Tests/DemoTests.cs @@ -40,6 +40,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests @@ -113,8 +114,8 @@ namespace Newtonsoft.Json.Tests // create hex string from value HtmlColor color = (HtmlColor)value; string hexString = color.Red.ToString("X2") - + color.Green.ToString("X2") - + color.Blue.ToString("X2"); + + color.Green.ToString("X2") + + color.Blue.ToString("X2"); // write value to json writer.WriteValue("#" + hexString); @@ -450,10 +451,13 @@ namespace Newtonsoft.Json.Tests public class House1 { public string StreetAddress { get; set; } + [JsonIgnore] public int Bedrooms { get; set; } + [JsonIgnore] public decimal FloorArea { get; set; } + [JsonIgnore] public DateTime BuildDate { get; set; } } @@ -463,6 +467,7 @@ namespace Newtonsoft.Json.Tests { [JsonProperty] public string StreetAddress { get; set; } + public int Bedrooms { get; set; } public decimal FloorArea { get; set; } public DateTime BuildDate { get; set; } @@ -473,6 +478,7 @@ namespace Newtonsoft.Json.Tests { [JsonProperty("address")] public string StreetAddress { get; set; } + public int Bedrooms { get; set; } public decimal FloorArea { get; set; } public DateTime BuildDate { get; set; } @@ -483,8 +489,10 @@ namespace Newtonsoft.Json.Tests { [JsonProperty("address", Order = 2)] public string StreetAddress { get; set; } + public int Bedrooms { get; set; } public decimal FloorArea { get; set; } + [JsonProperty("buildDate", Order = 1)] public DateTime BuildDate { get; set; } } @@ -494,8 +502,10 @@ namespace Newtonsoft.Json.Tests { [JsonProperty("address", Order = 2)] public string StreetAddress { get; set; } + public int Bedrooms { get; set; } public decimal FloorArea { get; set; } + [JsonProperty("buildDate", Order = 1)] [JsonConverter(typeof(JavaScriptDateTimeConverter))] public DateTime BuildDate { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs index da8f4ce3..f3cd803f 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs @@ -183,4 +183,5 @@ namespace Newtonsoft.Json.Tests.Documentation } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs index 7958c9cc..e8cd9f36 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs @@ -186,5 +186,6 @@ namespace Newtonsoft.Json.Tests.Documentation } } } + #pragma warning restore 618 #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs index f75d4a41..a9f6d721 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs @@ -92,7 +92,9 @@ namespace Newtonsoft.Json.Tests.Documentation // this will only be called once and then cached if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset)) + { contract.Converter = new JavaScriptDateTimeConverter(); + } return contract; } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs index cb118c97..3edd483d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs @@ -113,9 +113,13 @@ namespace Newtonsoft.Json.Tests.Documentation while (reader.Read()) { if (reader.Value != null) + { Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); + } else + { Console.WriteLine("Token: {0}", reader.TokenType); + } } // Token: StartObject diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBson.cs index 341a9ec4..755c7e8a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBson.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBsonCollection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBsonCollection.cs index e4d57fb2..6c8d3eca 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBsonCollection.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/DeserializeFromBsonCollection.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/SerializeToBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/SerializeToBson.cs index 25929592..6237e926 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/SerializeToBson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Bson/SerializeToBson.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Bson diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs index f46c8da2..0a8bad20 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs @@ -36,13 +36,15 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif #if !(DNXCORE50 || NET20) namespace Newtonsoft.Json.Tests.Documentation.Samples.Json { -#region Types + + #region Types public class XmlJsonReader : JsonReader { private readonly Stack _stateStack; @@ -65,7 +67,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override bool Read() { if (HandleValueType()) + { return true; + } while (_reader.Read()) { @@ -74,7 +78,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json case XmlNodeType.Element: string typeName = _reader.GetAttribute("type"); if (typeName == null) + { throw new Exception("No type specified."); + } _valueType = (JTokenType)Enum.Parse(typeof(JTokenType), typeName, true); @@ -100,25 +106,33 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json SetToken(JsonToken.EndObject); _stateStack.Pop(); if (PeekState() == JTokenType.Property) + { _stateStack.Pop(); + } return true; case JTokenType.Array: SetToken(JsonToken.EndArray); _stateStack.Pop(); if (PeekState() == JTokenType.Property) + { _stateStack.Pop(); + } return true; case JTokenType.Constructor: SetToken(JsonToken.EndConstructor); _stateStack.Pop(); if (PeekState() == JTokenType.Property) + { _stateStack.Pop(); + } return true; } _stateStack.Pop(); if (PeekState() == JTokenType.Property) + { _stateStack.Pop(); + } break; case XmlNodeType.Text: @@ -168,7 +182,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json _valueType = null; if (PeekState() == JTokenType.Property) + { _stateStack.Pop(); + } return true; case JTokenType.Object: SetToken(JsonToken.StartObject); @@ -183,7 +199,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json case JTokenType.Constructor: string constructorName = _reader.GetAttribute("name"); if (constructorName == null) + { throw new Exception("No constructor name specified."); + } SetToken(JsonToken.StartConstructor, constructorName); _stateStack.Push(JTokenType.Constructor); @@ -196,7 +214,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override int? ReadAsInt32() { if (!Read()) + { return null; + } return (Value != null) ? (int?)Convert.ToInt32(Value) : null; } @@ -204,7 +224,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override string ReadAsString() { if (!Read()) + { return null; + } return (string)Value; } @@ -212,7 +234,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override byte[] ReadAsBytes() { if (!Read()) + { return null; + } return (byte[])Value; } @@ -220,7 +244,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override decimal? ReadAsDecimal() { if (!Read()) + { return null; + } return (Value != null) ? (decimal?)Convert.ToDecimal(Value) : null; } @@ -228,7 +254,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override DateTime? ReadAsDateTime() { if (!Read()) + { return null; + } return (Value != null) ? (DateTime?)Convert.ToDateTime(Value) : null; } @@ -236,12 +264,14 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json public override DateTimeOffset? ReadAsDateTimeOffset() { if (!Read()) + { return null; + } return (Value != null) ? (DateTimeOffset?)Convert.ToDateTime(Value) : null; } } -#endregion + #endregion [TestFixture] public class CustomJsonReader : TestFixtureBase @@ -249,7 +279,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json [Test] public void Example() { -#region Usage + #region Usage string xml = @" This is a string! @@ -308,7 +338,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json // "Constructor": new Date(2000, 12, 30) //} } -#endregion + #endregion using (XmlReader xmlReader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings { IgnoreWhitespace = true })) using (XmlJsonReader reader = new XmlJsonReader(xmlReader)) diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs index 34fe3acf..58030b81 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs @@ -36,13 +36,15 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif #if !(DNXCORE50 || NET20) namespace Newtonsoft.Json.Tests.Documentation.Samples.Json { -#region Types + + #region Types public class XmlJsonWriter : JsonWriter { private readonly XmlWriter _writer; @@ -234,9 +236,13 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json base.WriteStartArray(); if (isStart) + { WriteValueElement("Root", JTokenType.Array); + } else + { WriteValueElement(JTokenType.Array); + } } public override void WriteStartObject() @@ -246,9 +252,13 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json base.WriteStartObject(); if (isStart) + { WriteValueElement("Root", JTokenType.Object); + } else + { WriteValueElement(JTokenType.Object); + } } public override void WriteStartConstructor(string name) @@ -258,9 +268,13 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json base.WriteStartConstructor(name); if (isStart) + { WriteValueElement("Root", JTokenType.Constructor); + } else + { WriteValueElement(JTokenType.Constructor); + } _writer.WriteAttributeString("name", name); } @@ -306,7 +320,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json } } } -#endregion + #endregion [TestFixture] public class CustomJsonWriter : TestFixtureBase @@ -314,17 +328,17 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json [Test] public void Example() { -#region Usage + #region Usage var user = new { Name = "James", Age = 30, Enabled = true, Roles = new[] - { - "Publisher", - "Administrator" - } + { + "Publisher", + "Administrator" + } }; StringWriter sw = new StringWriter(); @@ -348,7 +362,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json // Administrator // // -#endregion + #endregion sw = new StringWriter(); diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadJsonWithJsonTextReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadJsonWithJsonTextReader.cs index f3d3c94d..1e64b50c 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadJsonWithJsonTextReader.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadJsonWithJsonTextReader.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Json @@ -59,9 +60,13 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json while (reader.Read()) { if (reader.Value != null) + { Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); + } else + { Console.WriteLine("Token: {0}", reader.TokenType); + } } // Token: StartObject diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadMultipleContentWithJsonReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadMultipleContentWithJsonReader.cs index de65e897..5acc5da9 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadMultipleContentWithJsonReader.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/ReadMultipleContentWithJsonReader.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Json @@ -61,7 +62,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Json while (true) { if (!reader.Read()) + { break; + } JsonSerializer serializer = new JsonSerializer(); Role role = serializer.Deserialize(reader); diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/WriteJsonWithJsonTextWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/WriteJsonWithJsonTextWriter.cs index 18b3cf07..75ecefa6 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/WriteJsonWithJsonTextWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/WriteJsonWithJsonTextWriter.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Json diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/Clone.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/Clone.cs index 9659ed5b..dca4bad1 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/Clone.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/Clone.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonAnonymousObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonAnonymousObject.cs index 9eda1c3c..71cdbfe7 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonAnonymousObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonAnonymousObject.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonCollectionInitializer.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonCollectionInitializer.cs index e953d6b4..614ed3ca 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonCollectionInitializer.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonCollectionInitializer.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDeclaratively.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDeclaratively.cs index 1480d437..a290f4a8 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDeclaratively.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDeclaratively.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDynamic.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDynamic.cs index 458e07dd..f92c5875 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDynamic.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonDynamic.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonJTokenWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonJTokenWriter.cs index 128982ae..69c88383 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonJTokenWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonJTokenWriter.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonManually.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonManually.cs index 021c7746..dbe34d65 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonManually.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateJsonManually.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateReader.cs index 3bdf430e..c686668e 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateReader.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateReader.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq @@ -62,7 +63,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq { Console.Write(reader.TokenType); if (reader.Value != null) + { Console.Write(" - " + reader.Value); + } Console.WriteLine(); } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateWriter.cs index e8388b39..ac9a2106 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/CreateWriter.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeepEquals.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeepEquals.cs index 6daad3a4..0f589e43 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeepEquals.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeepEquals.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs index 2b6c669f..e50dfddc 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs @@ -41,6 +41,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/FromObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/FromObject.cs index 149b1cf4..a66d4a36 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/FromObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/FromObject.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JObjectProperties.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JObjectProperties.cs index fcdb0535..64d6a56a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JObjectProperties.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JObjectProperties.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JTokenAnnotation.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JTokenAnnotation.cs index bb1eb932..7777b2ae 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JTokenAnnotation.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JTokenAnnotation.cs @@ -59,7 +59,6 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq o["age"] = 59; o["employer"] = "Bill & Melinda Gates Foundation"; - HashSet changedProperties = o.Annotation>(); // age // employer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueCast.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueCast.cs index 4b5c90a7..7fa7ac29 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueCast.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueCast.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueValue.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueValue.cs index dabc8a6e..436ec0c8 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueValue.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/JValueValue.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/MergeJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/MergeJson.cs index 15f19374..db3d53c1 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/MergeJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/MergeJson.cs @@ -30,6 +30,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ModifyJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ModifyJson.cs index 76ad12b3..7d76be40 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ModifyJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ModifyJson.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonAny.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonAny.cs index b1d115e7..1ae1d083 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonAny.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonAny.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonArray.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonArray.cs index d6f9fba9..71ebd65d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonArray.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonArray.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonObject.cs index 0579a80e..9dc84073 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ParseJsonObject.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJson.cs index b6afc56d..95257aaa 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJson.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonDynamic.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonDynamic.cs index 8bf160dc..7db8b040 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonDynamic.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonDynamic.cs @@ -40,6 +40,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonLinq.cs index 317d5970..9e07f5e2 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonLinq.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonLinq.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectToken.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectToken.cs index 7bc7d123..9514505b 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectToken.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectToken.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectTokenWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectTokenWithLinq.cs index 53ad3e7b..a71ad8b6 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectTokenWithLinq.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/QueryJsonSelectTokenWithLinq.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJTokenFromBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJTokenFromBson.cs index 441b9508..2dfb2395 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJTokenFromBson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJTokenFromBson.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJson.cs index b14d120b..8a2c732d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ReadJson.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs index e9838f1e..806090c8 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs @@ -41,6 +41,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectComplex.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectComplex.cs index 67152497..5704c90d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectComplex.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectComplex.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectGeneric.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectGeneric.cs index 68856e25..cd8d9cb9 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectGeneric.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectGeneric.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectType.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectType.cs index 611b1369..f48dfb06 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectType.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToObjectType.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToString.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToString.cs index d7edd749..5149aefb 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToString.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToString.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToStringJsonConverter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToStringJsonConverter.cs index d7d3181d..239e5dba 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToStringJsonConverter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/ToStringJsonConverter.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteJTokenToBson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteJTokenToBson.cs index 4e6020c5..98cb4b39 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteJTokenToBson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteJTokenToBson.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteToJsonFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteToJsonFile.cs index 247ebdc1..89b0dd47 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteToJsonFile.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/WriteToJsonFile.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Linq diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/CreateJsonSchemaManually.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/CreateJsonSchemaManually.cs index 9a94bb5d..d80b7fb4 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/CreateJsonSchemaManually.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/CreateJsonSchemaManually.cs @@ -82,4 +82,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValid.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValid.cs index 40989227..6575e8bc 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValid.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValid.cs @@ -62,4 +62,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValidWithMessages.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValidWithMessages.cs index 34869910..64fae8c8 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValidWithMessages.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenIsValidWithMessages.cs @@ -72,4 +72,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenValidateWithEvent.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenValidateWithEvent.cs index 7010ad4f..ebfbb317 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenValidateWithEvent.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JTokenValidateWithEvent.cs @@ -71,4 +71,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonSchemaParse.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonSchemaParse.cs index 5ae67e02..cc4e5577 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonSchemaParse.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonSchemaParse.cs @@ -64,4 +64,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonValidatingReaderAndSerializer.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonValidatingReaderAndSerializer.cs index bc64ed2c..5c2bd56d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonValidatingReaderAndSerializer.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/JsonValidatingReaderAndSerializer.cs @@ -84,4 +84,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/LoadJsonSchemaFromFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/LoadJsonSchemaFromFile.cs index 2ddb4d2e..217a0eeb 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/LoadJsonSchemaFromFile.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/LoadJsonSchemaFromFile.cs @@ -50,4 +50,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/RefJsonSchemaResolver.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/RefJsonSchemaResolver.cs index a82cd1ca..d20b4e26 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/RefJsonSchemaResolver.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/RefJsonSchemaResolver.cs @@ -80,4 +80,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/SaveJsonSchemaToFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/SaveJsonSchemaToFile.cs index 24accfd0..b78ad39b 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/SaveJsonSchemaToFile.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Schema/SaveJsonSchemaToFile.cs @@ -55,4 +55,5 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomContractResolver.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomContractResolver.cs index 49c3b8df..2b0b901b 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomContractResolver.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomContractResolver.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomJsonConverter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomJsonConverter.cs index 782decd5..c400b39a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomJsonConverter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomJsonConverter.cs @@ -38,6 +38,7 @@ using NUnit.Framework; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs index 11edc9d1..0d2de30a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif #if !(DNXCORE50 || NET20 || NET35) @@ -43,7 +44,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer [TestFixture] public class CustomTraceWriter : TestFixtureBase { -#region Types + #region Types public class NLogTraceWriter : ITraceWriter { private static readonly Logger Logger = LogManager.GetLogger("NLogTraceWriter"); @@ -84,12 +85,12 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer } } } -#endregion + #endregion [Test] public void Example() { -#region Usage + #region Usage IList countries = new List { "New Zealand", @@ -110,7 +111,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer // "Denmark", // "China" // ] -#endregion + #endregion Assert.AreEqual(@"[ ""New Zealand"", diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DataContractAndDataMember.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DataContractAndDataMember.cs index 46af7d38..ad20a4cb 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DataContractAndDataMember.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DataContractAndDataMember.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueAttributeIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueAttributeIgnore.cs index cd33e45a..b9dca803 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueAttributeIgnore.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueAttributeIgnore.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueHandlingIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueHandlingIgnore.cs index d4613fbe..357ba5a1 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueHandlingIgnore.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DefaultValueHandlingIgnore.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeAnonymousType.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeAnonymousType.cs index 64bdf201..01228631 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeAnonymousType.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeAnonymousType.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCollection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCollection.cs index 4978ac72..e0e95010 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCollection.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCollection.cs @@ -37,6 +37,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeConstructorHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeConstructorHandling.cs index 8de0cd3f..2b78fc26 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeConstructorHandling.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeConstructorHandling.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer @@ -52,7 +53,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer public Website(Website website) { if (website == null) + { throw new ArgumentNullException("website"); + } Url = website.Url; } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCustomCreationConverter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCustomCreationConverter.cs index 47907e6a..08586544 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCustomCreationConverter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeCustomCreationConverter.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs index afd0b366..88576578 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs index 5f49f782..ab887401 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDictionary.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDictionary.cs index bc11d465..066adc98 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDictionary.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDictionary.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeMissingMemberHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeMissingMemberHandling.cs index 6b3697a1..2714cbc6 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeMissingMemberHandling.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeMissingMemberHandling.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObject.cs index 25a38506..0c172430 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObject.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObjectCreationHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObjectCreationHandling.cs index bc4baac5..9502e7c2 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObjectCreationHandling.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeObjectCreationHandling.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs index 747026f1..0fcafd38 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs @@ -63,7 +63,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer // use Autofac to create types that have been registered with it if (_container.IsRegistered(objectType)) + { contract.DefaultCreator = () => _container.Resolve(objectType); + } return contract; } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingAttribute.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingAttribute.cs index 0bbe8e9a..211afea0 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingAttribute.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingAttribute.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer @@ -54,7 +55,9 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer get { if (_roles == null) + { throw new Exception("Roles not loaded!"); + } return _roles; } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingEvent.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingEvent.cs index ad5ba271..1b2a6b5e 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingEvent.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ErrorHandlingEvent.cs @@ -34,6 +34,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeClass.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeClass.cs index a6da12c0..5bf65fd2 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeClass.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeClass.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeProperty.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeProperty.cs index 0cc05e17..4e036385 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeProperty.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonConverterAttributeProperty.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOptIn.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOptIn.cs index 1f4f5bd4..566d29a0 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOptIn.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOptIn.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOverrideIEnumerable.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOverrideIEnumerable.cs index 25712b22..abe67709 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOverrideIEnumerable.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonObjectAttributeOverrideIEnumerable.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyItemLevelSetting.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyItemLevelSetting.cs index b76fcbcc..f9df4182 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyItemLevelSetting.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyItemLevelSetting.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyName.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyName.cs index 7bc65942..4c0a7661 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyName.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyName.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyOrder.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyOrder.cs index 128c241a..cbc2e1a0 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyOrder.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyOrder.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyPropertyLevelSetting.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyPropertyLevelSetting.cs index 6def5973..8361d38a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyPropertyLevelSetting.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyPropertyLevelSetting.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyRequired.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyRequired.cs index f5e10dcb..532b636e 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyRequired.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyRequired.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/MaxDepth.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/MaxDepth.cs index 9f31e2e6..7c96876c 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/MaxDepth.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/MaxDepth.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/NullValueHandlingIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/NullValueHandlingIgnore.cs index 71d7acd5..c11a9218 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/NullValueHandlingIgnore.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/NullValueHandlingIgnore.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PopulateObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PopulateObject.cs index d0d7387f..1a76cb21 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PopulateObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PopulateObject.cs @@ -37,6 +37,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PreserveReferencesHandlingObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PreserveReferencesHandlingObject.cs index c4e44145..b2ea71c1 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PreserveReferencesHandlingObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PreserveReferencesHandlingObject.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PropertyJsonIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PropertyJsonIgnore.cs index eccfd3ed..796ddaae 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PropertyJsonIgnore.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/PropertyJsonIgnore.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ReferenceLoopHandlingIgnore.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ReferenceLoopHandlingIgnore.cs index bb1ff8b7..59ca5cda 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ReferenceLoopHandlingIgnore.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/ReferenceLoopHandlingIgnore.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializationCallbackAttributes.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializationCallbackAttributes.cs index b698f077..0bfc6231 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializationCallbackAttributes.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializationCallbackAttributes.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeCollection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeCollection.cs index 762cfd57..443a1f60 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeCollection.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeCollection.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeConditionalProperty.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeConditionalProperty.cs index 493c8320..6ba36979 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeConditionalProperty.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeConditionalProperty.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeContractResolver.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeContractResolver.cs index e13ad69d..c913261d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeContractResolver.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeContractResolver.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs index b80bcb0d..559d83c2 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatHandling.cs index f57b0113..1105b55b 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatHandling.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatHandling.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatString.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatString.cs index 0b6e1fcd..0834dba7 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatString.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateFormatString.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateTimeZoneHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateTimeZoneHandling.cs index 844c1d31..98f17b03 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateTimeZoneHandling.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDateTimeZoneHandling.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDictionary.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDictionary.cs index 78239fc3..68c87e1f 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDictionary.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDictionary.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeExtensionData.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeExtensionData.cs index f1f2b0bf..80504551 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeExtensionData.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeExtensionData.cs @@ -42,6 +42,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer public class SerializeExtensionData : TestFixtureBase { #pragma warning disable 169 + #region Types public class CustomerInvoice { @@ -53,6 +54,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer private IDictionary _additionalData; } #endregion + #pragma warning restore 169 [Test] diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeObject.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeObject.cs index c7c84e6e..38ffad96 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeObject.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeObject.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeRawJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeRawJson.cs index 179b830f..8d689607 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeRawJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeRawJson.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeSerializationBinder.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeSerializationBinder.cs index 2baae0b8..441d25a1 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeSerializationBinder.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeSerializationBinder.cs @@ -40,6 +40,7 @@ using NUnit.Framework; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeTypeNameHandling.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeTypeNameHandling.cs index 6ce4fce2..b86ee24c 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeTypeNameHandling.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeTypeNameHandling.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeUnindentedJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeUnindentedJson.cs index ae740583..eb99e9c5 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeUnindentedJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeUnindentedJson.cs @@ -32,6 +32,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonConverters.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonConverters.cs index 1289f28a..90e4e0a6 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonConverters.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonConverters.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonSerializerToFile.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonSerializerToFile.cs index f19874aa..cdf6e063 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonSerializerToFile.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeWithJsonSerializerToFile.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/TraceWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/TraceWriter.cs index 20703e76..ba1cdd7e 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/TraceWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/TraceWriter.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertJsonToXml.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertJsonToXml.cs index 6eeff5c9..484a19e7 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertJsonToXml.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertJsonToXml.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs index 404424fc..6010ec9a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif #if !(DNXCORE50 || NET20) @@ -45,7 +46,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml [Test] public void Example() { -#region Usage + #region Usage string xml = @" @@ -84,7 +85,7 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml // ] // } // } -#endregion + #endregion Assert.AreEqual(@"{""?xml"":{""@version"":""1.0"",""@standalone"":""no""},""root"":{""person"":[{""@id"":""1"",""name"":""Alan"",""url"":""http://www.google.com""},{""@id"":""2"",""name"":""Louis"",""url"":""http://www.yahoo.com""}]}}", json); } diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs index 41fd8a67..be83962a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif #if !(NET20 || DNXCORE50) diff --git a/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs index eda5de72..de53557f 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs @@ -263,7 +263,9 @@ namespace Newtonsoft.Json.Tests.Documentation { // only log an error once if (args.CurrentObject == args.ErrorContext.OriginalObject) + { errors.Add(args.ErrorContext.Error.Message); + } }; #endregion } @@ -281,7 +283,9 @@ namespace Newtonsoft.Json.Tests.Documentation get { if (_roles == null) + { throw new Exception("Roles not loaded!"); + } return _roles; } @@ -917,4 +921,5 @@ namespace Newtonsoft.Json.Tests.Documentation } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/ExceptionTests.cs b/Src/Newtonsoft.Json.Tests/ExceptionTests.cs index 28701014..669299b5 100644 --- a/Src/Newtonsoft.Json.Tests/ExceptionTests.cs +++ b/Src/Newtonsoft.Json.Tests/ExceptionTests.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests diff --git a/Src/Newtonsoft.Json.Tests/FileSystemEntityModel.edmx b/Src/Newtonsoft.Json.Tests/FileSystemEntityModel.edmx index f0a34e3f..87fb1b32 100644 --- a/Src/Newtonsoft.Json.Tests/FileSystemEntityModel.edmx +++ b/Src/Newtonsoft.Json.Tests/FileSystemEntityModel.edmx @@ -1,13 +1,17 @@  + - + - - + + @@ -65,7 +69,8 @@ - + @@ -84,9 +89,11 @@ - + - + @@ -94,11 +101,15 @@ - + - - - + + + @@ -113,7 +124,8 @@ - + @@ -134,7 +146,8 @@ - + @@ -142,7 +155,8 @@ - + @@ -170,15 +184,21 @@ - - + + - + + - + + + + \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs b/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs index 03d9e61e..7f63c492 100644 --- a/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonArrayAttributeTests.cs @@ -33,6 +33,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests diff --git a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs index 1244b05f..3b405fd9 100644 --- a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs @@ -53,6 +53,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests @@ -1201,7 +1202,6 @@ namespace Newtonsoft.Json.Tests writer.Flush(); } - #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) [Test] public void IntegerLengthOverflows() @@ -1292,7 +1292,7 @@ namespace Newtonsoft.Json.Tests } public ClobberingJsonConverter(string clobberValueString) - : this(clobberValueString, 1337) + : this(clobberValueString, 1337) { } @@ -1342,7 +1342,6 @@ namespace Newtonsoft.Json.Tests string json = JsonConvert.SerializeObject(measurements); - Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json); } @@ -1393,7 +1392,7 @@ namespace Newtonsoft.Json.Tests { throw new NotImplementedException(); } - + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(Math.Round((double)value, _precision, _rounding)); @@ -1403,12 +1402,22 @@ namespace Newtonsoft.Json.Tests [Test] public void GenericBaseClassSerialization() { - string json = JsonConvert.SerializeObject (new NonGenericChildClass ()); - Assert.AreEqual ("{\"Data\":null}", json); + string json = JsonConvert.SerializeObject(new NonGenericChildClass()); + Assert.AreEqual("{\"Data\":null}", json); } - public class GenericBaseClass { public virtual T Data { get; set; } } - public class GenericIntermediateClass : GenericBaseClass { public override string Data { get; set; } } - public class NonGenericChildClass : GenericIntermediateClass { } + public class GenericBaseClass + { + public virtual T Data { get; set; } + } + + public class GenericIntermediateClass : GenericBaseClass + { + public override string Data { get; set; } + } + + public class NonGenericChildClass : GenericIntermediateClass + { + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs index 3778f7cc..f1086ddd 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs @@ -134,6 +134,7 @@ namespace Newtonsoft.Json.Tests Assert.AreEqual(4, jsonTextReader.LineNumber); Assert.AreEqual(1, jsonTextReader.LinePosition); } + [Test] public void ReadCommentInsideArray() { @@ -923,9 +924,10 @@ third line", jsonTextReader.Value); [Test] public void NullTextReader() { - ExceptionAssert.Throws ( - () => { new JsonTextReader (null); }, - new string[] { + ExceptionAssert.Throws( + () => { new JsonTextReader(null); }, + new string[] + { "Value cannot be null." + Environment.NewLine + "Parameter name: reader", "Argument cannot be null." + Environment.NewLine + "Parameter name: reader" // Mono }); @@ -2837,10 +2839,10 @@ third line", jsonTextReader.Value); {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + -@",//comment after comma" + StringUtils.CarriageReturnLineFeed + -@"""ExpiryDate""://comment" + StringUtils.LineFeed + -@"new " + StringUtils.LineFeed + -@"Date + @",//comment after comma" + StringUtils.CarriageReturnLineFeed + + @"""ExpiryDate""://comment" + StringUtils.LineFeed + + @"new " + StringUtils.LineFeed + + @"Date (//comment null//comment ), @@ -3089,7 +3091,6 @@ null//comment reader.Read(); - reader = new JsonTextReader(new StringReader(json)); reader.Read(); @@ -3296,7 +3297,6 @@ null//comment Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType); Assert.IsTrue(reader.Read()); - reader = new JsonTextReader(new StringReader(json)); reader.DateParseHandling = Json.DateParseHandling.DateTimeOffset; @@ -3468,7 +3468,9 @@ null//comment public override int Read(char[] buffer, int index, int count) { if (Error) + { throw new Exception("Read error"); + } return _inner.Read(buffer, index, 1); } diff --git a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs index acbb43dc..e5c58ec9 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs @@ -35,7 +35,6 @@ using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Xml; - #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; @@ -47,8 +46,6 @@ using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif - - using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; @@ -893,15 +890,9 @@ namespace Newtonsoft.Json.Tests { jsonWriter.WriteToken(JsonToken.StartArray); - ExceptionAssert.Throws(() => - { - jsonWriter.WriteToken(JsonToken.Integer, "three"); - }, "Input string was not in a correct format."); + ExceptionAssert.Throws(() => { jsonWriter.WriteToken(JsonToken.Integer, "three"); }, "Input string was not in a correct format."); - ExceptionAssert.Throws(() => - { - jsonWriter.WriteToken(JsonToken.Integer); - }, @"Value cannot be null. + ExceptionAssert.Throws(() => { jsonWriter.WriteToken(JsonToken.Integer); }, @"Value cannot be null. Parameter name: value"); } } @@ -1324,7 +1315,9 @@ _____'propertyName': NaN, string oldText = swOld.ToString(); if (newText != oldText) + { throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); + } c++; } while (c != char.MaxValue); @@ -1336,7 +1329,9 @@ _____'propertyName': NaN, { // leading delimiter if (appendDelimiters) + { writer.Write(delimiter); + } if (s != null) { @@ -1350,7 +1345,9 @@ _____'propertyName': NaN, // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) + { continue; + } string escapedValue; @@ -1395,7 +1392,9 @@ _____'propertyName': NaN, if (c <= '\u001f') { if (unicodeBuffer == null) + { unicodeBuffer = new char[6]; + } StringUtils.ToCharAsUnicode(c, unicodeBuffer); @@ -1410,12 +1409,16 @@ _____'propertyName': NaN, } if (escapedValue == null) + { continue; + } if (i > lastWritePosition) { if (chars == null) + { chars = s.ToCharArray(); + } // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); @@ -1423,9 +1426,13 @@ _____'propertyName': NaN, lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) + { writer.Write(escapedValue); + } else + { writer.Write(unicodeBuffer); + } } if (lastWritePosition == 0) @@ -1436,7 +1443,9 @@ _____'propertyName': NaN, else { if (chars == null) + { chars = s.ToCharArray(); + } // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); @@ -1445,7 +1454,9 @@ _____'propertyName': NaN, // trailing delimiter if (appendDelimiters) + { writer.Write(delimiter); + } } [Test] @@ -1505,7 +1516,7 @@ true//comment after true" + StringUtils.CarriageReturn + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + - @"Constructor + @"Constructor (//comment null//comment ), @@ -1562,12 +1573,16 @@ null//comment SetWriteState(JsonToken.PropertyName, name); if (QuoteName) + { _writer.Write(QuoteChar); + } _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) + { _writer.Write(QuoteChar); + } _writer.Write(':'); } @@ -1594,9 +1609,13 @@ null//comment protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) + { _writer.Write("}}}"); + } else + { base.WriteEnd(token); + } } } @@ -1678,7 +1697,9 @@ null//comment public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) + { return _value; + } throw new Exception("Type not supported: " + conversionType.FullName); } diff --git a/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs b/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs index 79be8db4..a20ecd13 100644 --- a/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs @@ -1753,4 +1753,5 @@ namespace Newtonsoft.Json.Tests } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs b/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs index 35d36199..cce50368 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs @@ -17,6 +17,7 @@ using TestAttribute = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Linq @@ -173,7 +174,7 @@ namespace Newtonsoft.Json.Tests.Linq Assert.AreEqual(null, s); o.AddAnnotation("A string 4!"); - + s = o.Annotation(); Assert.AreEqual("A string 4!", s); @@ -277,7 +278,6 @@ namespace Newtonsoft.Json.Tests.Linq o["age"] = 59; o["employer"] = "Bill & Melinda Gates Foundation"; - HashSet changedProperties = o.Annotation>(); // age // employer diff --git a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs index 80ebcd81..36f11127 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs @@ -125,7 +125,7 @@ namespace Newtonsoft.Json.Tests.Linq foreach (dynamic friend in o.friends) { UpdateValueCount(counts, friend.id); - UpdateValueCount(counts, ((string) friend.name).Split(' ')[0]); + UpdateValueCount(counts, ((string)friend.name).Split(' ')[0]); } count++; @@ -863,7 +863,6 @@ namespace Newtonsoft.Json.Tests.Linq string oldRole = (string)oldAndBusted["Roles"][0]; // Admin - dynamic newHotness = new JObject(); newHotness.Name = "Arnie Admin"; newHotness.Enabled = true; diff --git a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs index 90e31f31..13fc4c1f 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs @@ -435,7 +435,6 @@ Parameter name: index"); } } - #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void ITypedListGetItemProperties() diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index 10a0ad9e..753acf87 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -97,7 +97,9 @@ namespace Newtonsoft.Json.Tests.Linq roles.Add(role); if (!reader.Read()) + { break; + } } Assert.AreEqual(2, roles.Count); @@ -121,7 +123,7 @@ namespace Newtonsoft.Json.Tests.Linq JToken o = JToken.Parse(json); - Assert.AreEqual("Apple", (string) o["Name"]); + Assert.AreEqual("Apple", (string)o["Name"]); } [Test] @@ -1940,7 +1942,9 @@ Parameter name: arrayIndex"); o.WriteTo(writer); } else + { token.WriteTo(writer); + } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs index eafe0c8d..5bd025bc 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs @@ -729,14 +729,14 @@ namespace Newtonsoft.Json.Tests.Linq JObject o = new JObject { - {"prop1", "value1"} + { "prop1", "value1" } }; JToken t1 = a[1][0]; JToken t2 = o["prop1"]; - List source = new List {t1, t2}; - + List source = new List { t1, t2 }; + List ancestors = source.AncestorsAndSelf().ToList(); Assert.AreEqual(6, ancestors.Count()); Assert.AreEqual(t1, ancestors[0]); @@ -760,7 +760,7 @@ namespace Newtonsoft.Json.Tests.Linq JObject o = new JObject { - {"prop1", "value1"} + { "prop1", "value1" } }; JToken t1 = a[1][0]; @@ -809,7 +809,7 @@ namespace Newtonsoft.Json.Tests.Linq JObject o = new JObject { - {"prop1", "value1"} + { "prop1", "value1" } }; List source = new List { a, o }; @@ -859,7 +859,7 @@ namespace Newtonsoft.Json.Tests.Linq JObject o = new JObject { - {"prop1", "value1"} + { "prop1", "value1" } }; List source = new List { a, o }; diff --git a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs index e888e481..19da08e0 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs @@ -765,9 +765,9 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath new JProperty("prop", new JArray( values.Select(v => new JObject(new JProperty("childProp", v))) + ) ) - ) - ); + ); IList t = o.SelectTokens("$.prop[?(@.childProp =='ff2dc672-6e15-4aa2-afb0-18f4f69596ad')]").ToList(); Assert.AreEqual(2, t.Count); diff --git a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathParseTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathParseTests.cs index 6428cebe..b5955605 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathParseTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathParseTests.cs @@ -42,6 +42,7 @@ using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Linq.JsonPath @@ -479,8 +480,8 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath { JPath path = new JPath("Blah[0]..Two.Three[1].Four"); Assert.AreEqual(6, path.Filters.Count); - Assert.AreEqual("Blah", ((FieldFilter) path.Filters[0]).Name); - Assert.AreEqual(0, ((ArrayIndexFilter) path.Filters[1]).Index); + Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); + Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[1]).Index); Assert.AreEqual("Two", ((ScanFilter)path.Filters[2]).Name); Assert.AreEqual("Three", ((FieldFilter)path.Filters[3]).Name); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[4]).Index); diff --git a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/QueryExpressionTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/QueryExpressionTests.cs index 415df2d5..5b27247f 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/QueryExpressionTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/QueryExpressionTests.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Linq.JsonPath @@ -80,29 +81,29 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath JObject o1 = new JObject { - {"Title","Title!"}, - {"FirstName", "FirstName!"}, - {"LastName", "LastName!"} + { "Title", "Title!" }, + { "FirstName", "FirstName!" }, + { "LastName", "LastName!" } }; Assert.IsTrue(compositeExpression.IsMatch(o1)); JObject o2 = new JObject { - {"Title","Title!"}, - {"FirstName", "FirstName!"} + { "Title", "Title!" }, + { "FirstName", "FirstName!" } }; Assert.IsFalse(compositeExpression.IsMatch(o2)); JObject o3 = new JObject { - {"Title","Title!"} + { "Title", "Title!" } }; Assert.IsFalse(compositeExpression.IsMatch(o3)); } - + [Test] public void OrExpressionTest() { @@ -138,24 +139,24 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath JObject o1 = new JObject { - {"Title","Title!"}, - {"FirstName", "FirstName!"}, - {"LastName", "LastName!"} + { "Title", "Title!" }, + { "FirstName", "FirstName!" }, + { "LastName", "LastName!" } }; Assert.IsTrue(compositeExpression.IsMatch(o1)); JObject o2 = new JObject { - {"Title","Title!"}, - {"FirstName", "FirstName!"} + { "Title", "Title!" }, + { "FirstName", "FirstName!" } }; Assert.IsTrue(compositeExpression.IsMatch(o2)); JObject o3 = new JObject { - {"Title","Title!"} + { "Title", "Title!" } }; Assert.IsFalse(compositeExpression.IsMatch(o3)); @@ -195,4 +196,4 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath Assert.IsFalse(e2.IsMatch(new JArray(4, 5))); } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs index d2a86f1c..1feb3079 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs @@ -722,7 +722,7 @@ keyword such as type of business."" Post p = new Post { Title = "How to use FromObject", - Categories = new [] { "LINQ to JSON" } + Categories = new[] { "LINQ to JSON" } }; // serialize Post to JSON then parse JSON – SLOW! @@ -1110,8 +1110,8 @@ keyword such as type of business."" } ] } -}", o.ToString()); - +}", o.ToString()); + CustomAssert.IsInstanceOfType(typeof(JObject), o); CustomAssert.IsInstanceOfType(typeof(JObject), o["channel"]); Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]); diff --git a/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs b/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs index add425d3..0701d07c 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs @@ -42,6 +42,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Linq @@ -103,10 +104,10 @@ namespace Newtonsoft.Json.Tests.Linq Property1 = new { SubProperty1 = 1 } }); var right = (JArray)JToken.FromObject(new object[] - { - new { Property1 = 1 }, - new { Property1 = 1 } - }); + { + new { Property1 = 1 }, + new { Property1 = 1 } + }); left.Merge(right); @@ -182,7 +183,6 @@ namespace Newtonsoft.Json.Tests.Linq Property2 = 3, Property3 = new { - }, Property5 = (object)null } @@ -282,25 +282,25 @@ namespace Newtonsoft.Json.Tests.Linq public void MergeMismatchingTypesInArray() { var left = (JArray)JToken.FromObject(new object[] - { - true, - null, - new { Property1 = 1 }, - new object[] { 1 }, - new { Property1 = 1 }, - 1, - new object[] { 1 } - }); + { + true, + null, + new { Property1 = 1 }, + new object[] { 1 }, + new { Property1 = 1 }, + 1, + new object[] { 1 } + }); var right = (JArray)JToken.FromObject(new object[] - { - 1, - 5, - new object[] { 1 }, - new { Property1 = 1 }, - true, - new { Property1 = 1 }, - null - }); + { + 1, + 5, + new object[] { 1 }, + new { Property1 = 1 }, + true, + new { Property1 = 1 }, + null + }); left.Merge(right, new JsonMergeSettings { diff --git a/Src/Newtonsoft.Json.Tests/LinqToSql/Department.cs b/Src/Newtonsoft.Json.Tests/LinqToSql/Department.cs index 2ef99598..4b3ecfe7 100644 --- a/Src/Newtonsoft.Json.Tests/LinqToSql/Department.cs +++ b/Src/Newtonsoft.Json.Tests/LinqToSql/Department.cs @@ -42,4 +42,5 @@ namespace Newtonsoft.Json.Tests.LinqToSql } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClasses.dbml b/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClasses.dbml index 4929619b..bde4a7aa 100644 --- a/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClasses.dbml +++ b/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClasses.dbml @@ -1,12 +1,17 @@ - + + + - - + +
@@ -21,15 +26,18 @@ - - + +
- +
\ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClassesSerializationTests.cs b/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClassesSerializationTests.cs index 26dcfb3b..e35f59e4 100644 --- a/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClassesSerializationTests.cs +++ b/Src/Newtonsoft.Json.Tests/LinqToSql/LinqToSqlClassesSerializationTests.cs @@ -134,4 +134,5 @@ namespace Newtonsoft.Json.Tests.LinqToSql } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net20.project.json b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net20.project.json index da699258..4014ab61 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net20.project.json +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net20.project.json @@ -6,6 +6,6 @@ "net20": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net35.project.json b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net35.project.json index 3bbf3282..e1ed027e 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net35.project.json +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net35.project.json @@ -6,6 +6,6 @@ "net35": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net40.project.json b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net40.project.json index 32527e95..8ce5c394 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net40.project.json +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Net40.project.json @@ -7,6 +7,6 @@ "net40": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.project.json b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.project.json index cc0e4b7f..693a3fa0 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.project.json +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.project.json @@ -8,6 +8,6 @@ "net45": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable40.project.json b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable40.project.json index dee49009..c46b1171 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable40.project.json +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable40.project.json @@ -7,6 +7,6 @@ "net40": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.project.json b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.project.json index fc81f703..1ff92079 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.project.json +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.project.json @@ -9,6 +9,6 @@ "net45": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs index 8d56f959..4be5157d 100644 --- a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs +++ b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs @@ -345,7 +345,6 @@ namespace Newtonsoft.Json.Tests ""Property5"":""5"" }"; - var watch = new Stopwatch(); watch.Start(); for (long iteration = 0; iteration < totalIterations; ++iteration) @@ -584,7 +583,6 @@ If attributes are not mentioned, default values are used in each case. test.dictionary = new Dictionary { { "Val & asd1", 1 }, { "Val2 & asd1", 3 }, { "Val3 & asd1", 4 } }; - test.Address1.Street = "fff Street"; test.Address1.Entered = DateTime.Now.AddDays(20); @@ -811,7 +809,9 @@ If attributes are not mentioned, default values are used in each case. GC.Collect(); if (warmUp) + { Deserialize(method, json); + } Stopwatch timed = new Stopwatch(); timed.Start(); @@ -841,7 +841,9 @@ If attributes are not mentioned, default values are used in each case. //serializer.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; //serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; if (isoDateTimeConverter) + { serializer.Converters.Add(new IsoDateTimeConverter()); + } var value = (T)serializer.Deserialize(new StringReader(json), type); return value; @@ -973,7 +975,9 @@ If attributes are not mentioned, default values are used in each case. return DeserializeJsonNet((string)json, true); case SerializeMethod.JsonNetManual: if (typeof(T) == typeof(TestClass)) + { return (T)(object)DeserializeJsonNetManual((string)json); + } return default(T); case SerializeMethod.JsonNetBinary: @@ -1020,9 +1024,13 @@ If attributes are not mentioned, default values are used in each case. }; if (rootValue == null) + { rootValue = currentValue; + } if (parentValue != null) + { parentValue.Child = currentValue; + } parentValue = currentValue; } @@ -1206,7 +1214,6 @@ If attributes are not mentioned, default values are used in each case. private Address _Address1 = new Address(); - [DataMember] public List
Addresses { diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index eb7a3cdc..846978b1 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -44,6 +44,7 @@ using System.Security; #elif NET40 [assembly: AssemblyTitle("Json.NET Tests .NET 4.0")] #else + [assembly: AssemblyTitle("Json.NET Tests")] #endif @@ -76,4 +77,4 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("7.0.0.0")] -[assembly: AssemblyFileVersion("7.0.2.18802")] +[assembly: AssemblyFileVersion("7.0.2.18802")] \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs b/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs index 48a48953..42acfd49 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs @@ -43,6 +43,7 @@ using System.IO; using Newtonsoft.Json.Tests.TestObjects; #if !(NETFX_CORE || DNXCORE50) using System.Data; + #endif namespace Newtonsoft.Json.Tests.Schema @@ -185,7 +186,9 @@ namespace Newtonsoft.Json.Tests.Schema token.Validate(typeSchema, (sender, args) => { errors.Add(args.Message); }); if (errors.Count > 0) + { Assert.Fail("Schema generated for type '{0}' is not valid." + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray()), typeof(T)); + } } [Test] @@ -460,4 +463,5 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs index 6350ab25..85d5f4d7 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaBuilderTests.cs @@ -645,4 +645,5 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs index f5322b53..e935400a 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs @@ -52,6 +52,7 @@ using Extensions = Newtonsoft.Json.Schema.Extensions; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Schema @@ -353,7 +354,9 @@ namespace Newtonsoft.Json.Tests.Schema protected override JsonContract CreateContract(Type objectType) { if (objectType == typeof(DirectoryInfo)) + { return base.CreateObjectContract(objectType); + } return base.CreateContract(objectType); } @@ -849,4 +852,5 @@ namespace Newtonsoft.Json.Tests.Schema { } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs index 20526a30..50ac5ce8 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaModelBuilderTests.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Schema @@ -171,4 +172,5 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs index a18881bf..b22be7a9 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaNodeTests.cs @@ -35,6 +35,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Schema @@ -123,4 +124,5 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs index b7b83db6..70466269 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaSpecTests.cs @@ -119,5 +119,6 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #endif #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs index 6cd77392..835d3de3 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaTests.cs @@ -39,6 +39,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Schema @@ -152,7 +153,6 @@ namespace Newtonsoft.Json.Tests.Schema } }", newJson); - json = @"{ ""type"":""object"", ""extends"":[{""type"":""string""}], @@ -177,7 +177,6 @@ namespace Newtonsoft.Json.Tests.Schema } }", newJson); - json = @"{ ""type"":""object"", ""extends"":[{""type"":""string""},{""type"":""object""}], @@ -586,4 +585,5 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Schema/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/Schema/PerformanceTests.cs index fee730c5..0f2ccbdb 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/PerformanceTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/PerformanceTests.cs @@ -40,6 +40,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Schema @@ -174,7 +175,9 @@ namespace Newtonsoft.Json.Tests.Schema { _stopwatch.Stop(); if (_callback != null) + { _callback(Result); + } } public TimeSpan Result @@ -183,4 +186,5 @@ namespace Newtonsoft.Json.Tests.Schema } } } + #pragma warning restore 618 \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs index f4ff2f84..c00cca5e 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs @@ -44,6 +44,7 @@ using NUnit.Framework; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -175,10 +176,13 @@ namespace Newtonsoft.Json.Tests.Serialization { [DefaultValue("parameter1_default")] public string Parameter1 { get; private set; } + [DefaultValue("parameter2_default")] public string Parameter2 { get; private set; } + [DefaultValue("parameter3_default")] public string Parameter3 { get; set; } + [DefaultValue("parameter4_default")] public string Parameter4 { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs index a6e16db3..6b71dd21 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs @@ -102,7 +102,9 @@ namespace Newtonsoft.Json.Tests.Serialization protected override JsonContract CreateContract(Type objectType) { if (objectType == typeof(Employee)) + { objectType = typeof(IPerson); + } return base.CreateContract(objectType); } @@ -129,7 +131,7 @@ namespace Newtonsoft.Json.Tests.Serialization p.PropertyType = typeof(int); - Assert.AreEqual(0 , p.GetResolvedDefaultValue()); + Assert.AreEqual(0, p.GetResolvedDefaultValue()); Assert.AreEqual(null, p.DefaultValue); p.PropertyType = typeof(DateTime); @@ -223,7 +225,7 @@ namespace Newtonsoft.Json.Tests.Serialization } public class CustomList : List - { + { } [Test] @@ -487,7 +489,7 @@ namespace Newtonsoft.Json.Tests.Serialization contract.OverrideCreator = args => { ensureCustomCreatorCalled = true; - return new MultipleParamatrizedConstructorsJsonConstructor((string) args[0], (int) args[1]); + return new MultipleParamatrizedConstructorsJsonConstructor((string)args[0], (int)args[1]); }; #pragma warning disable 618 Assert.IsNull(contract.OverrideConstructor); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs index fc2cf0d8..eb5d02cc 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DefaultValueHandlingTests.cs @@ -56,6 +56,7 @@ namespace Newtonsoft.Json.Tests.Serialization public MyEnum Status { get; set; } private string _data; + public string Data { get { return _data; } @@ -82,7 +83,7 @@ namespace Newtonsoft.Json.Tests.Serialization string json = "{\"Data\":\"Other with some more text\"}"; MyClass result = JsonConvert.DeserializeObject(json, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate }); - + Assert.AreEqual(MyEnum.Other, result.Status); } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs index 4c929c59..2c790713 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs @@ -43,6 +43,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -140,7 +141,9 @@ namespace Newtonsoft.Json.Tests.Serialization // use Autofac to create types that have been registered with it if (_container.IsRegistered(objectType)) + { contract.DefaultCreator = () => _container.Resolve(objectType); + } return contract; } @@ -248,4 +251,5 @@ namespace Newtonsoft.Json.Tests.Serialization } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DynamicConcreteTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DynamicConcreteTests.cs index 264abcfa..4c6f7417 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DynamicConcreteTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DynamicConcreteTests.cs @@ -44,6 +44,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -59,7 +60,9 @@ namespace Newtonsoft.Json.Tests.Serialization // create a dynamic mock object for interfaces or abstract classes if (contract.CreatedType.IsInterface || contract.CreatedType.IsAbstract) + { contract.DefaultCreator = () => DynamicConcrete.GetInstanceFor(contract.CreatedType); + } return contract; } @@ -79,7 +82,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - public void UseDynamicConcreteIfTargetObjectTypeIsAnAbstractClassWithNoConcrete() + public void UseDynamicConcreteIfTargetObjectTypeIsAnAbstractClassWithNoConcrete() { string json = @"{Name:""Name!"", Game:""Same""}"; @@ -179,7 +182,9 @@ namespace Newtonsoft.Json.Tests.Serialization IncludeType(targetType, typeBuilder); foreach (var face in targetType.GetInterfaces()) + { IncludeType(face, typeBuilder); + } return typeBuilder.CreateType(); } @@ -189,7 +194,10 @@ namespace Newtonsoft.Json.Tests.Serialization var methodInfos = typeOfT.GetMethods(); foreach (var methodInfo in methodInfos) { - if (methodInfo.Name.StartsWith("set_")) continue; // we always add a set for a get. + if (methodInfo.Name.StartsWith("set_")) + { + continue; // we always add a set for a get. + } if (methodInfo.Name.StartsWith("get_")) { @@ -197,12 +205,21 @@ namespace Newtonsoft.Json.Tests.Serialization } else { - if (methodInfo.IsAbstract) BindMethod(typeBuilder, methodInfo); + if (methodInfo.IsAbstract) + { + BindMethod(typeBuilder, methodInfo); + } } } - if (typeOfT.IsInterface) typeBuilder.AddInterfaceImplementation(typeOfT); - else if (typeOfT.IsAbstract) typeBuilder.SetParent(typeOfT); + if (typeOfT.IsInterface) + { + typeBuilder.AddInterfaceImplementation(typeOfT); + } + else if (typeOfT.IsAbstract) + { + typeBuilder.SetParent(typeOfT); + } } static void BindMethod(TypeBuilder typeBuilder, MethodInfo methodInfo) @@ -230,7 +247,7 @@ namespace Newtonsoft.Json.Tests.Serialization else if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum) { var getMethod = typeof(Activator).GetMethod("CreateInstance", - new[] { typeof(Type) }); + new[] { typeof(Type) }); var lb = methodILGen.DeclareLocal(methodInfo.ReturnType); if (lb.LocalType != null) { @@ -261,19 +278,18 @@ namespace Newtonsoft.Json.Tests.Serialization //Getter var backingGet = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public | - MethodAttributes.SpecialName | MethodAttributes.Virtual | - MethodAttributes.HideBySig, propertyType, Type.EmptyTypes); + MethodAttributes.SpecialName | MethodAttributes.Virtual | + MethodAttributes.HideBySig, propertyType, Type.EmptyTypes); var getIl = backingGet.GetILGenerator(); getIl.Emit(OpCodes.Ldarg_0); getIl.Emit(OpCodes.Ldfld, backingField); getIl.Emit(OpCodes.Ret); - //Setter var backingSet = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public | - MethodAttributes.SpecialName | MethodAttributes.Virtual | - MethodAttributes.HideBySig, null, new[] { propertyType }); + MethodAttributes.SpecialName | MethodAttributes.Virtual | + MethodAttributes.HideBySig, null, new[] { propertyType }); var setIl = backingSet.GetILGenerator(); @@ -289,4 +305,5 @@ namespace Newtonsoft.Json.Tests.Serialization } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs index f8a19b7c..c73f1527 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs @@ -47,6 +47,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization diff --git a/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs index ad21c056..e4e2c1bc 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/EntitiesSerializationTests.cs @@ -41,6 +41,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ExtensionDataTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ExtensionDataTests.cs index bf3fc402..fc51d7bc 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ExtensionDataTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ExtensionDataTests.cs @@ -38,6 +38,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -829,10 +830,7 @@ namespace Newtonsoft.Json.Tests.Serialization public void SerializeExtensionData_NoGetter() { ExceptionAssert.Throws( - () => - { - JsonConvert.SerializeObject(new DocNoGetter()); - }, + () => { JsonConvert.SerializeObject(new DocNoGetter()); }, "Invalid extension data attribute on 'Newtonsoft.Json.Tests.Serialization.ExtensionDataTests+DocNoGetter'. Member 'Content' must have a getter."); } } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs index e8e0ca4c..e3e0ce42 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs @@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void List() { - FSharpList l = ListModule.OfSeq(new List {1,2,3}); + FSharpList l = ListModule.OfSeq(new List { 1, 2, 3 }); string json = JsonConvert.SerializeObject(l, Formatting.Indented); @@ -91,4 +91,5 @@ namespace Newtonsoft.Json.Tests.Serialization } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ImmutableCollectionsTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ImmutableCollectionsTests.cs index b4293240..1d61ae87 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ImmutableCollectionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ImmutableCollectionsTests.cs @@ -108,11 +108,11 @@ namespace Newtonsoft.Json.Tests.Serialization public void SerializeArray() { ImmutableArray l = ImmutableArray.CreateRange(new List - { - "One", - "II", - "3" - }); + { + "One", + "II", + "3" + }); string json = JsonConvert.SerializeObject(l, Formatting.Indented); StringAssert.AreEqual(@"[ @@ -440,4 +440,5 @@ namespace Newtonsoft.Json.Tests.Serialization #endregion } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs index e50dfdac..a7196a4d 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs @@ -52,6 +52,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -349,7 +350,7 @@ namespace Newtonsoft.Json.Tests.Serialization } }); - string json = JsonConvert.SerializeObject(d, Formatting.Indented); + string json = JsonConvert.SerializeObject(d, Formatting.Indented); Assert.AreEqual(@"{ ""key"": [ @@ -776,6 +777,7 @@ namespace Newtonsoft.Json.Tests.Serialization ]", json); } #endif + [Test] public void TestEscapeDictionaryStrings() { @@ -1182,7 +1184,7 @@ namespace Newtonsoft.Json.Tests.Serialization Array3D aa = new Array3D(); aa.Before = "Before!"; aa.After = "After!"; - aa.Coordinates = new[, ,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } }; + aa.Coordinates = new[,,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } }; string json = JsonConvert.SerializeObject(aa); @@ -1195,7 +1197,7 @@ namespace Newtonsoft.Json.Tests.Serialization Array3DWithConverter aa = new Array3DWithConverter(); aa.Before = "Before!"; aa.After = "After!"; - aa.Coordinates = new[, ,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } }; + aa.Coordinates = new[,,] { { { 1, 1, 1 }, { 1, 1, 2 } }, { { 1, 2, 1 }, { 1, 2, 2 } }, { { 2, 1, 1 }, { 2, 1, 2 } }, { { 2, 2, 1 }, { 2, 2, 2 } } }; string json = JsonConvert.SerializeObject(aa, Formatting.Indented); @@ -1954,7 +1956,7 @@ namespace Newtonsoft.Json.Tests.Serialization public class Array3D { public string Before { get; set; } - public int[, ,] Coordinates { get; set; } + public int[,,] Coordinates { get; set; } public string After { get; set; } } @@ -1963,7 +1965,7 @@ namespace Newtonsoft.Json.Tests.Serialization public string Before { get; set; } [JsonProperty(ItemConverterType = typeof(IntToFloatConverter))] - public int[, ,] Coordinates { get; set; } + public int[,,] Coordinates { get; set; } public string After { get; set; } } @@ -1997,7 +1999,9 @@ namespace Newtonsoft.Json.Tests.Serialization } } else + { yield break; + } } IEnumerator IEnumerable.GetEnumerator() diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 9022076f..54d96deb 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -88,6 +88,7 @@ using System.Linq; #endif #if !(NETFX_CORE || DNXCORE50) using System.Drawing; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -101,11 +102,13 @@ namespace Newtonsoft.Json.Tests.Serialization string Name { get; set; } bool P1 { get; } } + public interface ISubclass : ISubclassBase { new bool P1 { get; set; } int P2 { get; set; } } + public interface IMainClass { int ID { get; set; } @@ -120,6 +123,7 @@ namespace Newtonsoft.Json.Tests.Serialization public bool P1 { get; set; } public int P2 { get; set; } } + public class MainClass : IMainClass { public int ID { get; set; } @@ -139,6 +143,7 @@ namespace Newtonsoft.Json.Tests.Serialization P2 = 44 }; } + public static IMainClass InstantiateManiClass() { return new MainClass @@ -243,19 +248,13 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void CoercedEmptyStringWithRequired() { - ExceptionAssert.Throws(() => - { - JsonConvert.DeserializeObject("{requiredProperty:''}"); - }, "Required property 'RequiredProperty' expects a value but got null. Path '', line 1, position 21."); + ExceptionAssert.Throws(() => { JsonConvert.DeserializeObject("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a value but got null. Path '', line 1, position 21."); } [Test] public void CoercedEmptyStringWithRequired_DisallowNull() { - ExceptionAssert.Throws(() => - { - JsonConvert.DeserializeObject("{requiredProperty:''}"); - }, "Required property 'RequiredProperty' expects a non-null value. Path '', line 1, position 21."); + ExceptionAssert.Throws(() => { JsonConvert.DeserializeObject("{requiredProperty:''}"); }, "Required property 'RequiredProperty' expects a non-null value. Path '', line 1, position 21."); } [Test] @@ -268,10 +267,7 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void CoercedEmptyStringWithRequiredConstructor() { - ExceptionAssert.Throws(() => - { - JsonConvert.DeserializeObject("{Bars:''}"); - }, "Required property 'Bars' expects a value but got null. Path '', line 1, position 9."); + ExceptionAssert.Throws(() => { JsonConvert.DeserializeObject("{Bars:''}"); }, "Required property 'Bars' expects a value but got null. Path '', line 1, position 9."); } public class IgnoredProperty @@ -279,6 +275,7 @@ namespace Newtonsoft.Json.Tests.Serialization [JsonIgnore] [JsonProperty(Required = Required.Always)] public string StringProp1 { get; set; } + [JsonIgnore] public string StringProp2 { get; set; } } @@ -306,10 +303,7 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void Serialize_Required_DisallowedNull() { - ExceptionAssert.Throws(() => - { - JsonConvert.SerializeObject(new Binding_DisallowNull()); - }, "Cannot write a null value for property 'RequiredProperty'. Property requires a non-null value. Path ''."); + ExceptionAssert.Throws(() => { JsonConvert.SerializeObject(new Binding_DisallowNull()); }, "Cannot write a null value for property 'RequiredProperty'. Property requires a non-null value. Path ''."); } [Test] @@ -331,10 +325,7 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void Serialize_ItemRequired_DisallowedNull() { - ExceptionAssert.Throws(() => - { - JsonConvert.SerializeObject(new DictionaryWithNoNull()); - }, "Cannot write a null value for property 'Name'. Property requires a non-null value. Path ''."); + ExceptionAssert.Throws(() => { JsonConvert.SerializeObject(new DictionaryWithNoNull()); }, "Cannot write a null value for property 'Name'. Property requires a non-null value. Path ''."); } public class DictionaryKeyContractResolver : DefaultContractResolver @@ -510,10 +501,13 @@ namespace Newtonsoft.Json.Tests.Serialization { [JsonIgnore] public Version IgnoredProperty { get; set; } + [JsonIgnore] public List IgnoredList { get; set; } + [JsonIgnore] public Dictionary IgnoredDictionary { get; set; } + [JsonProperty(Required = Required.Always)] public string Name { get; set; } } @@ -523,7 +517,9 @@ namespace Newtonsoft.Json.Tests.Serialization public override JsonContract ResolveContract(Type type) { if (type == typeof(Version)) + { throw new Exception("Error!"); + } return base.ResolveContract(type); } @@ -868,7 +864,6 @@ namespace Newtonsoft.Json.Tests.Serialization protected SimpleResponse() { - } protected SimpleResponse(string message) @@ -966,10 +961,7 @@ namespace Newtonsoft.Json.Tests.Serialization { string json = "['1.2.3.4444444444444444444444']"; - ExceptionAssert.Throws(() => - { - JsonConvert.DeserializeObject>(json); - }, @"Error converting value ""1.2.3.4444444444444444444444"" to type 'System.Version'. Path '[0]', line 1, position 31."); + ExceptionAssert.Throws(() => { JsonConvert.DeserializeObject>(json); }, @"Error converting value ""1.2.3.4444444444444444444444"" to type 'System.Version'. Path '[0]', line 1, position 31."); } [Test] @@ -1365,7 +1357,9 @@ namespace Newtonsoft.Json.Tests.Serialization private void OnDeserializedMethod(StreamingContext context) { if (_serializationInfo == null) + { return; + } _stringValue = _serializationInfo.GetString("stringValue"); _intValue = _serializationInfo.GetInt32("intValue"); @@ -2786,7 +2780,6 @@ keyword such as type of business."" Assert.AreEqual("LastNameValue", personRaw.LastName); } - [Test] public void DeserializeNullableMember() { @@ -4157,7 +4150,6 @@ Path '', line 1, position 1."); string Value { get; set; } } - public class KeyValueId : IKeyValueId { public int Id { get; set; } @@ -4190,9 +4182,13 @@ Path '', line 1, position 1."); var item = this[id]; if (item == null) + { Add(value); + } else + { _dict1[item.Key] = value; + } } } @@ -4207,7 +4203,9 @@ Path '', line 1, position 1."); set { foreach (var item in value) + { Add(item); + } } } } @@ -5227,9 +5225,13 @@ Path '', line 1, position 1."); Pos p = (Pos)value; if (p != null) + { writer.WriteRawValue(String.Format("new Pos({0},{1})", p.X, p.Y)); + } else + { writer.WriteNull(); + } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) @@ -5250,9 +5252,13 @@ Path '', line 1, position 1."); PosDouble p = (PosDouble)value; if (p != null) + { writer.WriteRawValue(String.Format(CultureInfo.InvariantCulture, "new PosD({0},{1})", p.X, p.Y)); + } else + { writer.WriteNull(); + } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) @@ -5371,8 +5377,6 @@ Path '', line 1, position 1."); Assert.AreEqual(9.9m, dic["value"]); } - - public class DictionaryKey { public string Value { get; set; } @@ -5575,7 +5579,7 @@ Path '', line 1, position 1."); JsonTextReader reader = new JsonTextReader(new StringReader(serializeObject)); reader.DateParseHandling = DateParseHandling.None; - + JsonSerializer serializer = new JsonSerializer(); var deserializeObject = serializer.Deserialize(reader); @@ -5885,7 +5889,6 @@ Path '', line 1, position 1."); Assert.AreEqual(deserialized.Foo2, null); } - private static NullableStructPropertyClass deserialize(string serStr) { return JsonConvert.DeserializeObject( @@ -7143,7 +7146,8 @@ Path '', line 1, position 1."); { ExceptionAssert.Throws( () => { JsonConvert.DeserializeObject(null); }, - new [] { + new[] + { "Value cannot be null." + Environment.NewLine + "Parameter name: value", "Argument cannot be null." + Environment.NewLine + "Parameter name: value" // mono }); @@ -7154,7 +7158,8 @@ Path '', line 1, position 1."); { ExceptionAssert.Throws( () => { JsonConvert.DeserializeObject(null); }, - new [] { + new[] + { "Value cannot be null." + Environment.NewLine + "Parameter name: value", "Argument cannot be null." + Environment.NewLine + "Parameter name: value" // mono }); @@ -7339,7 +7344,9 @@ Path '', line 1, position 1."); while (true) { if (!reader.Read()) + { break; + } JsonSerializer serializer = new JsonSerializer(); MultipleItemsClass foo = serializer.Deserialize(reader); @@ -8526,7 +8533,9 @@ Path '', line 1, position 1."); public FooConstructor(string bar) { if (bar == null) + { throw new ArgumentNullException("bar"); + } Bar = bar; } @@ -9212,7 +9221,6 @@ Path '', line 1, position 1."); public string DerivedProperty { get; private set; } } - public class BaseConstructorType { [JsonProperty] @@ -9293,11 +9301,7 @@ Path '', line 1, position 1."); public class NullableLongTestClass { - public ulong? Value - { - get; - set; - } + public ulong? Value { get; set; } } #endif @@ -9346,13 +9350,13 @@ Path '', line 1, position 1."); }"; ExceptionAssert.Throws(() => - { - JsonConvert.DeserializeObject( - JsonMessage, - new MailAddressReadConverter(), - new AttachmentReadConverter(), - new EncodingReadConverter()); - }, + { + JsonConvert.DeserializeObject( + JsonMessage, + new MailAddressReadConverter(), + new AttachmentReadConverter(), + new EncodingReadConverter()); + }, "Cannot populate list type System.Net.Mime.HeaderCollection. Path 'Headers', line 26, position 14."); } @@ -9436,7 +9440,9 @@ Path '', line 1, position 1."); { var encodingName = serializer.Deserialize(reader); if (encodingName == null) + { return null; + } return Encoding.GetEncoding(encodingName); } @@ -9455,7 +9461,6 @@ Path '', line 1, position 1."); public string DerivedProperty { get; private set; } } - public class BaseWithPrivate { [JsonProperty] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs index f8a55263..d61736c5 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs @@ -40,6 +40,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs index 76028912..551da37c 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs @@ -37,6 +37,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization diff --git a/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs index 9061faae..5361a968 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/NullValueHandlingTests.cs @@ -36,6 +36,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs index cef68449..438b0676 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs @@ -37,6 +37,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs index acfb92ac..ffe6609d 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs @@ -40,6 +40,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -141,7 +142,6 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual(true, c2.ListA[0].B.SomeValue); } - public class Parent { public Child ReadOnlyChild diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs index 27adf4e6..a2e28b54 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs @@ -317,7 +317,7 @@ namespace Newtonsoft.Json.Tests.Serialization // put objects in a bucket based on their reference return RuntimeHelpers.GetHashCode(obj); #else - // put all objects in the same bucket so ReferenceEquals is called on all + // put all objects in the same bucket so ReferenceEquals is called on all return -1; #endif } @@ -332,7 +332,9 @@ namespace Newtonsoft.Json.Tests.Serialization { AccountWithEquals a = obj as AccountWithEquals; if (a == null) + { return false; + } return Name == a.Name; } @@ -340,7 +342,9 @@ namespace Newtonsoft.Json.Tests.Serialization public override int GetHashCode() { if (Name == null) + { return 0; + } return Name.GetHashCode(); } @@ -359,7 +363,9 @@ namespace Newtonsoft.Json.Tests.Serialization get { if (_accessCount >= 3) + { return null; + } _accessCount++; return new List(_data); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs index 6f8c428e..dad49a58 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs @@ -42,6 +42,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -60,9 +61,7 @@ namespace Newtonsoft.Json.Tests.Serialization public int TestField; public ReflectionTestObject( - [DefaultValue("1")] - [JsonProperty] - int testParameter) + [DefaultValue("1")] [JsonProperty] int testParameter) { TestProperty = testParameter; TestField = testParameter; diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs index 30082d49..24e61fd0 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs @@ -70,14 +70,15 @@ namespace Newtonsoft.Json.Tests.Serialization } ]"; - var possibleMsgs = new [] { + var possibleMsgs = new[] + { "[1] - Error message for member 1 = An item with the same key has already been added.", "[1] - Error message for member 1 = An element with the same key already exists in the dictionary." // mono }; VersionKeyedCollection c = JsonConvert.DeserializeObject(json); Assert.AreEqual(1, c.Count); Assert.AreEqual(1, c.Messages.Count); - Assert.IsTrue (possibleMsgs.Any (m => m == c.Messages[0]), "Expected One of: " + Environment.NewLine + string.Join (Environment.NewLine, possibleMsgs) + Environment.NewLine + "Was: " + Environment.NewLine + c.Messages[0]); + Assert.IsTrue(possibleMsgs.Any(m => m == c.Messages[0]), "Expected One of: " + Environment.NewLine + string.Join(Environment.NewLine, possibleMsgs) + Environment.NewLine + "Was: " + Environment.NewLine + c.Messages[0]); } [Test] @@ -166,7 +167,9 @@ namespace Newtonsoft.Json.Tests.Serialization Error = (s, e) => { if (e.CurrentObject.GetType().IsArray) + { e.ErrorContext.Handled = true; + } } }); @@ -294,7 +297,6 @@ namespace Newtonsoft.Json.Tests.Serialization ""2000-12-01T00:00:00Z"" ]"))); - // 2009-09-09T00:00:00Z // 1977-02-20T00:00:00Z // 2000-12-01T00:00:00Z @@ -309,19 +311,20 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]); Assert.AreEqual(3, errors.Count); - var possibleErrs = new [] { + var possibleErrs = new[] + { #if !(NET20 || NET35) "[1] - 1 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.", "[1] - 1 - String was not recognized as a valid DateTime." #else - // handle typo fix in later versions of .NET + // handle typo fix in later versions of .NET "[1] - 1 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.", "[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0." #endif }; - Assert.IsTrue(possibleErrs.Any (m => m == errors[0]), - "Expected One of: " + string.Join (Environment.NewLine, possibleErrs) + Environment.NewLine + "But was: " + errors[0]); + Assert.IsTrue(possibleErrs.Any(m => m == errors[0]), + "Expected One of: " + string.Join(Environment.NewLine, possibleErrs) + Environment.NewLine + "But was: " + errors[0]); Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray. Path '[2]', line 4, position 9.", errors[1]); Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime. Path '[4]', line 8, position 12.", errors[2]); @@ -395,7 +398,9 @@ namespace Newtonsoft.Json.Tests.Serialization { // only log an error once if (args.CurrentObject == args.ErrorContext.OriginalObject) + { errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message); + } }; serializer.Deserialize(new StringReader(json), typeof(List>)); @@ -820,7 +825,6 @@ namespace Newtonsoft.Json.Tests.Serialization throw new NotImplementedException(); } } - } [Test] @@ -850,7 +854,7 @@ namespace Newtonsoft.Json.Tests.Serialization { Something = s }; - + var writer = new System.IO.StringWriter(); ExceptionAssert.Throws(() => { serialiser.Serialize(writer, r); }, "An error occurred."); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs index 1dbafda5..3f2f9c74 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs @@ -104,7 +104,10 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual(expectedError, obj.Member5); DerivedSerializationEventTestObject derivedObj = obj as DerivedSerializationEventTestObject; - if (derivedObj != null) Assert.AreEqual("This value was set after deserialization.", derivedObj.Member7); + if (derivedObj != null) + { + Assert.AreEqual("This value was set after deserialization.", derivedObj.Member7); + } } } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ShouldSerializeTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ShouldSerializeTests.cs index bb23115c..3dfbceb2 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ShouldSerializeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ShouldSerializeTests.cs @@ -46,6 +46,7 @@ using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; + #endif namespace Newtonsoft.Json.Tests.Serialization @@ -60,6 +61,7 @@ namespace Newtonsoft.Json.Tests.Serialization public class B { public A A { get; set; } + public virtual bool ShouldSerializeA() { return false; @@ -83,26 +85,33 @@ namespace Newtonsoft.Json.Tests.Serialization 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()} - } - }, - } + 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() } + } + }, + } } }; @@ -511,26 +520,19 @@ namespace Newtonsoft.Json.Tests.Serialization public class Foo1 { private Bar1 myBarField; + public Bar1 myBar { - get - { - return myBarField; - } + get { return myBarField; } set { myBarField = value; } } private string nameField; + public string name { - get - { - return nameField; - } - set - { - nameField = value; - } + get { return nameField; } + set { nameField = value; } } public virtual bool ShouldSerializemyBar() @@ -547,29 +549,22 @@ namespace Newtonsoft.Json.Tests.Serialization public class Bar1 { [JsonIgnore] - public bool ShouldSerializemyBazCalled { get; set;} + public bool ShouldSerializemyBazCalled { get; set; } private Baz1[] myBazField; + public Baz1[] myBaz { - get - { - return myBazField; - } + get { return myBazField; } set { myBazField = value; } } private string nameField; + public string name { - get - { - return nameField; - } - set - { - nameField = value; - } + get { return nameField; } + set { nameField = value; } } public virtual bool ShouldSerializemyBaz() @@ -587,22 +582,18 @@ namespace Newtonsoft.Json.Tests.Serialization public class Baz1 { private Frob1[] myFrobField; + public Frob1[] myFrob { - get - { - return myFrobField; - } + get { return myFrobField; } set { myFrobField = value; } } private string nameField; + public string name { - get - { - return nameField; - } + get { return nameField; } set { nameField = value; } } @@ -620,12 +611,10 @@ namespace Newtonsoft.Json.Tests.Serialization public class Frob1 { private string nameField; + public string name { - get - { - return nameField; - } + get { return nameField; } set { nameField = value; } } @@ -647,10 +636,7 @@ namespace Newtonsoft.Json.Tests.Serialization if (shouldDeserializeMethodInfo != null) { - property.ShouldDeserialize = o => - { - return (bool)shouldDeserializeMethodInfo.Invoke(o, null); - }; + property.ShouldDeserialize = o => { return (bool)shouldDeserializeMethodInfo.Invoke(o, null); }; } return property; @@ -660,7 +646,8 @@ namespace Newtonsoft.Json.Tests.Serialization public class ShouldDeserializeTestClass { [JsonExtensionData] - public IDictionary ExtensionData { get; set; } + public IDictionary ExtensionData { get; set; } + public bool HasName { get; set; } public string Name { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs index 5d65909c..833af7a9 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs @@ -132,7 +132,7 @@ namespace Newtonsoft.Json.Tests.Serialization { Dictionary dic = new Dictionary { - { "movie", new Movie { Name = "Die Hard"}} + { "movie", new Movie { Name = "Die Hard" } } }; string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings @@ -158,7 +158,7 @@ namespace Newtonsoft.Json.Tests.Serialization { IList> dic = new List> { - new KeyValuePair("movie", new Movie { Name = "Die Hard"}) + new KeyValuePair("movie", new Movie { Name = "Die Hard" }) }; string json = JsonConvert.SerializeObject(dic, Formatting.Indented, new JsonSerializerSettings @@ -760,7 +760,6 @@ namespace Newtonsoft.Json.Tests.Serialization // } //] - StringAssert.AreEqual(@"[ { ""$type"": ""Customer"", @@ -920,7 +919,6 @@ namespace Newtonsoft.Json.Tests.Serialization public string Url { get; set; } } - [Test] public void GenericDictionaryObject() { @@ -990,7 +988,6 @@ namespace Newtonsoft.Json.Tests.Serialization Assert.AreEqual(2, statues.Count); } - [Test] public void SerializingIEnumerableOfTShouldRetainGenericTypeInfo() { @@ -1033,14 +1030,18 @@ namespace Newtonsoft.Json.Tests.Serialization public IEnumerator GetEnumerator() { if (count == 0) // last node + { yield break; + } yield return value; var nextInLine = next; while (nextInLine != null) { if (nextInLine.count != 0) + { yield return nextInLine.value; + } nextInLine = nextInLine.next; } } @@ -1795,11 +1796,11 @@ namespace Newtonsoft.Json.Tests.Serialization string serialized = JsonConvert.SerializeObject(input, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormat = FormatterAssemblyStyle.Full } // TypeNameHandling.Auto will work - ); + ); var output = JsonConvert.DeserializeObject>>(serialized, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All } - ); + ); List strings = output.SelectMany(s => s).ToList(); @@ -1875,7 +1876,6 @@ namespace Newtonsoft.Json.Tests.Serialization public Dictionary> Rows { get; private set; } } - public interface IMyInterfaceType { string SomeProperty { get; set; } @@ -1964,7 +1964,9 @@ namespace Newtonsoft.Json.Tests.Serialization SerializableWrapper w = obj as SerializableWrapper; if (w == null) + { return false; + } return Equals(w.Content, Content); } @@ -1972,7 +1974,9 @@ namespace Newtonsoft.Json.Tests.Serialization public override int GetHashCode() { if (Content == null) + { return 0; + } return Content.GetHashCode(); } @@ -2007,8 +2011,14 @@ namespace Newtonsoft.Json.Tests.Serialization public override bool Equals(object obj) { - if (obj == null) return false; - if (ReferenceEquals(this, obj)) return true; + if (obj == null) + { + return false; + } + if (ReferenceEquals(this, obj)) + { + return true; + } if (obj is IExample) { return Name.Equals(((IExample)obj).Name); @@ -2022,7 +2032,9 @@ namespace Newtonsoft.Json.Tests.Serialization public override int GetHashCode() { if (Name == null) + { return 0; + } return Name.GetHashCode(); } @@ -2104,6 +2116,7 @@ namespace Newtonsoft.Json.Tests.Serialization { [DataMember] public int ID { get; set; } + [DataMember] public string Name { get; set; } } @@ -2122,4 +2135,5 @@ namespace Newtonsoft.Json.Tests.Serialization } #endif } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs index 4f49a77c..6e748b1c 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs @@ -147,7 +147,7 @@ namespace Newtonsoft.Json.Tests.Serialization #else [JsonIgnore] #endif - public string nonSerializedField; + public string nonSerializedField; public bool Equals(SerializableType other) { diff --git a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs index 52e694e4..f2afa241 100644 --- a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs +++ b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs @@ -54,6 +54,7 @@ using System.Collections; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests @@ -225,7 +226,9 @@ namespace Newtonsoft.Json.Tests { string hex = BitConverter.ToString(bytes); if (removeDashes) + { hex = hex.Replace("-", ""); + } return hex; } @@ -247,13 +250,19 @@ namespace Newtonsoft.Json.Tests // the % 32 handles lower case characters int b = (c - '0') % 32; // correction for a-f - if (b > 9) b -= 7; + if (b > 9) + { + b -= 7; + } // store nibble (4 bits) in byte array bytes[offset] |= (byte)(b << shift); // toggle the shift variable between 0 and 4 shift ^= 4; // move to next byte - if (shift != 0) offset++; + if (shift != 0) + { + offset++; + } } return bytes; } @@ -348,7 +357,9 @@ namespace Newtonsoft.Json.Tests public static string Normalize(string s) { if (s != null) + { s = Regex.Replace(s, "\r\n"); + } return s; } @@ -380,7 +391,9 @@ namespace Newtonsoft.Json.Tests } if (!match) + { throw new Exception("Unexpected exception message." + Environment.NewLine + "Expected one of: " + string.Join(Environment.NewLine, possibleMessages) + Environment.NewLine + "Got: " + ex.Message + Environment.NewLine + Environment.NewLine + ex); + } } } catch (Exception ex) diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs b/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs index 9fb1be18..2679de1e 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs @@ -29,6 +29,7 @@ using System.Collections; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.TestObjects diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Component.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Component.cs index 6082d35d..146d105b 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Component.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Component.cs @@ -25,8 +25,8 @@ namespace Newtonsoft.Json.Tests.TestObjects { - #if !(NET35 || NET20) - [JsonObject(MemberSerialization.OptIn)] +#if !(NET35 || NET20) + [JsonObject(MemberSerialization.OptIn)] public class Component { [JsonIgnore] // Ignore circular reference diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ConverterPrecedenceClassConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ConverterPrecedenceClassConverter.cs index d7531a48..a81ba6b9 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ConverterPrecedenceClassConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ConverterPrecedenceClassConverter.cs @@ -49,7 +49,9 @@ namespace Newtonsoft.Json.Tests.TestObjects string converter = (string)j[0]; if (converter != ConverterType) + { throw new Exception(StringUtils.FormatWith("Serialize converter {0} and deserialize converter {1} do not match.", CultureInfo.InvariantCulture, converter, ConverterType)); + } string testValue = (string)j[1]; return new ConverterPrecedenceClass(testValue); diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Currency.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Currency.cs index c4f328f2..0f6706c2 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Currency.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Currency.cs @@ -170,4 +170,5 @@ namespace Newtonsoft.Json.Tests.TestObjects } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Event.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Event.cs index cdb94caa..9486d555 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Event.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Event.cs @@ -77,10 +77,16 @@ namespace Newtonsoft.Json.Tests.TestObjects _summary = summary; _time = DateTime.Now; - if (_userId == 0) _userId = GetCurrentUserId(); + if (_userId == 0) + { + _userId = GetCurrentUserId(); + } //This call only works at top level for now. //If _stackTrace = Nothing Then _stackTrace = Environment.StackTrace - if (_sublocation == null) _sublocation = GetCurrentSubLocation(); + if (_sublocation == null) + { + _sublocation = GetCurrentSubLocation(); + } } public Event(string sublocation, int userId, EventType type, string summary, string details, string stackTrace, string tag) @@ -94,9 +100,15 @@ namespace Newtonsoft.Json.Tests.TestObjects _tag = tag; _time = DateTime.Now; - if (_userId == 0) _userId = GetCurrentUserId(); + if (_userId == 0) + { + _userId = GetCurrentUserId(); + } //If _stackTrace = Nothing Then _stackTrace = Environment.StackTrace - if (_sublocation == null) _sublocation = GetCurrentSubLocation(); + if (_sublocation == null) + { + _sublocation = GetCurrentSubLocation(); + } } public override string ToString() diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/GameObject.cs b/Src/Newtonsoft.Json.Tests/TestObjects/GameObject.cs index e4a8ca44..0bb4285b 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/GameObject.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/GameObject.cs @@ -46,4 +46,5 @@ namespace Newtonsoft.Json.Tests.TestObjects } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs b/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs index 84ea10f7..c99aaae2 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs @@ -50,10 +50,10 @@ namespace Newtonsoft.Json.Tests.TestObjects internal class MyInterfaceConverter : TypeConverter { private readonly List _writers = new List - { - new ConsoleWriter(), - new TraceWriter() - }; + { + new ConsoleWriter(), + new TraceWriter() + }; public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { @@ -68,7 +68,9 @@ namespace Newtonsoft.Json.Tests.TestObjects public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null) + { return null; + } return (from w in _writers where w.Name == value.ToString() select w).FirstOrDefault(); } @@ -77,7 +79,9 @@ namespace Newtonsoft.Json.Tests.TestObjects Type destinationType) { if (value == null) + { return null; + } return ((IMyInterface)value).Name; } } @@ -130,11 +134,11 @@ namespace Newtonsoft.Json.Tests.TestObjects return (from c in converters - let converter = - (TypeConverter)Activator.CreateInstance(Type.GetType(((TypeConverterAttribute)c).ConverterTypeName)) - where converter.CanConvertFrom(typeof(string)) - && converter.CanConvertTo(typeof(string)) - select converter) + let converter = + (TypeConverter)Activator.CreateInstance(Type.GetType(((TypeConverterAttribute)c).ConverterTypeName)) + where converter.CanConvertFrom(typeof(string)) + && converter.CanConvertTo(typeof(string)) + select converter) .FirstOrDefault(); } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ListErrorObject.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ListErrorObject.cs index 8a3a8e4e..ba3c291a 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ListErrorObject.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ListErrorObject.cs @@ -38,7 +38,9 @@ namespace Newtonsoft.Json.Tests.TestObjects get { if (_throwError != null) + { return _throwError; + } throw new Exception("ListErrorObject.ThrowError get error!"); } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/MetroStringConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/MetroStringConverter.cs index 0e18ff96..7b07e898 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/MetroStringConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/MetroStringConverter.cs @@ -43,7 +43,9 @@ namespace Newtonsoft.Json.Tests.TestObjects { string s = (string)reader.Value; if (s == null) + { return null; + } #if !(NETFX_CORE || DNXCORE50) return s.ToLower(CultureInfo.InvariantCulture).Trim(new[] { ':' }); diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/PersonError.cs b/Src/Newtonsoft.Json.Tests/TestObjects/PersonError.cs index c3c9e79f..f202cc0c 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/PersonError.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/PersonError.cs @@ -42,7 +42,9 @@ namespace Newtonsoft.Json.Tests.TestObjects get { if (_roles == null) + { throw new Exception("Roles not loaded!"); + } return _roles; } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/PublicParametizedConstructorRequiringConverterTestClass.cs b/Src/Newtonsoft.Json.Tests/TestObjects/PublicParametizedConstructorRequiringConverterTestClass.cs index 3c23aa90..31467032 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/PublicParametizedConstructorRequiringConverterTestClass.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/PublicParametizedConstructorRequiringConverterTestClass.cs @@ -39,9 +39,13 @@ namespace Newtonsoft.Json.Tests.TestObjects NameContainer nameContainer = value as NameContainer; if (nameContainer != null) + { writer.WriteValue(nameContainer.Value); + } else + { writer.WriteNull(); + } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Shape.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Shape.cs index 98b4eccf..dc097338 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Shape.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Shape.cs @@ -140,7 +140,6 @@ namespace Newtonsoft.Json.Tests.TestObjects } } - [Serializable, DebuggerDisplay("{__DebugDisplay(),nq}")] public class Prism : Shape { @@ -224,4 +223,5 @@ namespace Newtonsoft.Json.Tests.TestObjects } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/SqlTypesDataSet.xsd b/Src/Newtonsoft.Json.Tests/TestObjects/SqlTypesDataSet.xsd index e15a7c61..d77ec7e7 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/SqlTypesDataSet.xsd +++ b/Src/Newtonsoft.Json.Tests/TestObjects/SqlTypesDataSet.xsd @@ -1,21 +1,42 @@  - + + - + - + - + - + diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/VersionKeyedCollection.cs b/Src/Newtonsoft.Json.Tests/TestObjects/VersionKeyedCollection.cs index f283963c..90632abe 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/VersionKeyedCollection.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/VersionKeyedCollection.cs @@ -59,7 +59,9 @@ namespace Newtonsoft.Json.Tests.TestObjects for (int i = 0; i < Count; i++) { if (i % 2 == 0) + { throw new Exception("Index even: " + i); + } yield return this[i]; } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/WidgetIdJsonConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/WidgetIdJsonConverter.cs index e1f15309..2a50d5a4 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/WidgetIdJsonConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/WidgetIdJsonConverter.cs @@ -43,7 +43,9 @@ namespace Newtonsoft.Json.Tests.TestObjects public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) + { return null; + } return new WidgetId1 { Value = int.Parse(reader.Value.ToString()) }; } } diff --git a/Src/Newtonsoft.Json.Tests/Utilities/ConvertUtilsTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/ConvertUtilsTests.cs index 515a344b..4ceb163a 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/ConvertUtilsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/ConvertUtilsTests.cs @@ -161,26 +161,11 @@ namespace Newtonsoft.Json.Tests.Utilities [Test] public void HexParseError() { - ExceptionAssert.Throws(() => - { - ConvertUtils.HexTextToInt("-100".ToCharArray(), 0, 4); - }, "Invalid hex character: -"); - ExceptionAssert.Throws(() => - { - ConvertUtils.HexTextToInt("000g".ToCharArray(), 0, 4); - }, "Invalid hex character: g"); - ExceptionAssert.Throws(() => - { - ConvertUtils.HexTextToInt(" ssd".ToCharArray(), 0, 4); - }, "Invalid hex character: "); - ExceptionAssert.Throws(() => - { - ConvertUtils.HexTextToInt("000:".ToCharArray(), 0, 4); - }, "Invalid hex character: :"); - ExceptionAssert.Throws(() => - { - ConvertUtils.HexTextToInt("000G".ToCharArray(), 0, 4); - }, "Invalid hex character: G"); + ExceptionAssert.Throws(() => { ConvertUtils.HexTextToInt("-100".ToCharArray(), 0, 4); }, "Invalid hex character: -"); + ExceptionAssert.Throws(() => { ConvertUtils.HexTextToInt("000g".ToCharArray(), 0, 4); }, "Invalid hex character: g"); + ExceptionAssert.Throws(() => { ConvertUtils.HexTextToInt(" ssd".ToCharArray(), 0, 4); }, "Invalid hex character: "); + ExceptionAssert.Throws(() => { ConvertUtils.HexTextToInt("000:".ToCharArray(), 0, 4); }, "Invalid hex character: :"); + ExceptionAssert.Throws(() => { ConvertUtils.HexTextToInt("000G".ToCharArray(), 0, 4); }, "Invalid hex character: G"); } private void HexParseSame(string text) diff --git a/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs index 50fd200e..a4a93c52 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/DynamicReflectionDelegateFactoryTests.cs @@ -46,6 +46,7 @@ using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Utilities diff --git a/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs index ebe70c69..7888fd2c 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs @@ -113,11 +113,13 @@ namespace Newtonsoft.Json.Tests.Utilities public void DefaultConstructor_Abstract() { ExceptionAssert.Throws( - () => { + () => + { Func create = ExpressionReflectionDelegateFactory.Instance.CreateDefaultConstructor(typeof(Type)); create(); - }, new [] { + }, new[] + { "Cannot create an abstract class.", "Cannot create an abstract class 'System.Type'." // mono }); @@ -285,7 +287,8 @@ namespace Newtonsoft.Json.Tests.Utilities public void CreateGetWithBadObjectTarget() { ExceptionAssert.Throws( - () => { + () => + { Person p = new Person(); p.Name = "Hi"; @@ -293,7 +296,8 @@ namespace Newtonsoft.Json.Tests.Utilities setter(p); }, - new [] { + new[] + { "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.", "Cannot cast from source type to destination type." // mono }); @@ -303,7 +307,8 @@ namespace Newtonsoft.Json.Tests.Utilities public void CreateSetWithBadObjectTarget() { ExceptionAssert.Throws( - () => { + () => + { Person p = new Person(); Movie m = new Movie(); @@ -317,7 +322,8 @@ namespace Newtonsoft.Json.Tests.Utilities Assert.AreEqual(p.Name, "Hi"); }, - new [] { + new[] + { "Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.", "Cannot cast from source type to destination type." // mono }); @@ -327,13 +333,15 @@ namespace Newtonsoft.Json.Tests.Utilities public void CreateSetWithBadObjectValue() { ExceptionAssert.Throws( - () => { + () => + { Movie m = new Movie(); Action setter = ExpressionReflectionDelegateFactory.Instance.CreateSet(TestReflectionUtils.GetProperty(typeof(Movie), "Name")); setter(m, new Version("1.1.1.1")); - }, new [] { + }, new[] + { "Unable to cast object of type 'System.Version' to type 'System.String'.", "Cannot cast from source type to destination type." //mono }); @@ -356,4 +364,5 @@ namespace Newtonsoft.Json.Tests.Utilities } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Utilities/LateboundReflectionDelegateFactoryTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/LateboundReflectionDelegateFactoryTests.cs index bd85c1b3..e71a4c91 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/LateboundReflectionDelegateFactoryTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/LateboundReflectionDelegateFactoryTests.cs @@ -15,6 +15,7 @@ using NUnit.Framework; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Tests.Utilities diff --git a/Src/Newtonsoft.Json.Tests/large_sample.xml b/Src/Newtonsoft.Json.Tests/large_sample.xml index ab311959..cb2f0126 100644 --- a/Src/Newtonsoft.Json.Tests/large_sample.xml +++ b/Src/Newtonsoft.Json.Tests/large_sample.xml @@ -1,5 +1,7 @@ - - + + + Add diff --git a/Src/Newtonsoft.Json.sln.DotSettings b/Src/Newtonsoft.Json.sln.DotSettings index 2c4af6be..80c25a7e 100644 --- a/Src/Newtonsoft.Json.sln.DotSettings +++ b/Src/Newtonsoft.Json.sln.DotSettings @@ -1,6 +1,12 @@  + 1 + 1 False + False + False True + False + False False True True diff --git a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs index d2e09cdb..eb521512 100644 --- a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs @@ -142,9 +142,13 @@ namespace Newtonsoft.Json.Bson { DateTime dateTime = (DateTime)value.Value; if (DateTimeKindHandling == DateTimeKind.Utc) + { dateTime = dateTime.ToUniversalTime(); + } else if (DateTimeKindHandling == DateTimeKind.Local) + { dateTime = dateTime.ToLocalTime(); + } ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false); } @@ -193,7 +197,9 @@ namespace Newtonsoft.Json.Bson private void WriteString(string s, int byteCount, int? calculatedlengthPrefix) { if (calculatedlengthPrefix != null) + { _writer.Write(calculatedlengthPrefix.Value); + } WriteUtf8Bytes(s, byteCount); diff --git a/Src/Newtonsoft.Json/Bson/BsonObjectId.cs b/Src/Newtonsoft.Json/Bson/BsonObjectId.cs index 399e5f41..68bcd90b 100644 --- a/Src/Newtonsoft.Json/Bson/BsonObjectId.cs +++ b/Src/Newtonsoft.Json/Bson/BsonObjectId.cs @@ -47,7 +47,9 @@ namespace Newtonsoft.Json.Bson { ValidationUtils.ArgumentNotNull(value, "value"); if (value.Length != 12) + { throw new ArgumentException("An ObjectId must be 12 bytes", "value"); + } Value = value; } diff --git a/Src/Newtonsoft.Json/Bson/BsonReader.cs b/Src/Newtonsoft.Json/Bson/BsonReader.cs index aac3b406..0e388c9d 100644 --- a/Src/Newtonsoft.Json/Bson/BsonReader.cs +++ b/Src/Newtonsoft.Json/Bson/BsonReader.cs @@ -297,11 +297,13 @@ namespace Newtonsoft.Json.Bson base.Close(); if (CloseInput && _reader != null) + { #if !(DOTNET || PORTABLE40 || PORTABLE) _reader.Close(); #else _reader.Dispose(); #endif + } } private bool ReadCodeWScope() @@ -339,7 +341,9 @@ namespace Newtonsoft.Json.Bson case BsonReaderState.CodeWScopeScopeObject: bool result = ReadNormal(); if (result && TokenType == JsonToken.EndObject) + { _bsonReaderState = BsonReaderState.CodeWScopeScopeEnd; + } return result; case BsonReaderState.CodeWScopeScopeEnd: @@ -430,7 +434,9 @@ namespace Newtonsoft.Json.Bson case State.PostValue: ContainerContext context = _currentContext; if (context == null) + { return false; + } int lengthMinusEnd = context.Length - 1; @@ -451,11 +457,15 @@ namespace Newtonsoft.Json.Bson else if (context.Position == lengthMinusEnd) { if (ReadByte() != 0) + { throw JsonReaderException.Create(this, "Unexpected end of object byte value."); + } PopContext(); if (_currentContext != null) + { MovePosition(context.Length); + } JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray; SetToken(endToken); @@ -484,9 +494,13 @@ namespace Newtonsoft.Json.Bson { _stack.RemoveAt(_stack.Count - 1); if (_stack.Count == 0) + { _currentContext = null; + } else + { _currentContext = _stack[_stack.Count - 1]; + } } private void PushContext(ContainerContext newContext) @@ -509,9 +523,13 @@ namespace Newtonsoft.Json.Bson double d = ReadDouble(); if (_floatParseHandling == FloatParseHandling.Decimal) + { SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture)); + } else + { SetToken(JsonToken.Float, d); + } break; case BsonType.String: case BsonType.Symbol: @@ -663,7 +681,9 @@ namespace Newtonsoft.Json.Bson int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0); if (builder == null) + { builder = new StringBuilder(MaxCharBytesSize * 2); + } builder.Append(_charBuffer, 0, charCount); @@ -703,7 +723,9 @@ namespace Newtonsoft.Json.Bson private string GetString(int length) { if (length == 0) + { return string.Empty; + } EnsureBuffers(); @@ -722,7 +744,9 @@ namespace Newtonsoft.Json.Bson int byteCount = _reader.Read(_byteBuffer, offset, count); if (byteCount == 0) + { throw new EndOfStreamException("Unable to read beyond the end of the stream."); + } totalBytesRead += byteCount; @@ -742,7 +766,9 @@ namespace Newtonsoft.Json.Bson int lastFullCharStop = GetLastFullCharStop(byteCount - 1); if (builder == null) + { builder = new StringBuilder(length); + } int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0); builder.Append(_charBuffer, 0, charCount); @@ -798,10 +824,22 @@ namespace Newtonsoft.Json.Bson private int BytesInSequence(byte b) { - if (b <= SeqRange1[1]) return 1; - if (b >= SeqRange2[0] && b <= SeqRange2[1]) return 2; - if (b >= SeqRange3[0] && b <= SeqRange3[1]) return 3; - if (b >= SeqRange4[0] && b <= SeqRange4[1]) return 4; + if (b <= SeqRange1[1]) + { + return 1; + } + if (b >= SeqRange2[0] && b <= SeqRange2[1]) + { + return 2; + } + if (b >= SeqRange3[0] && b <= SeqRange3[1]) + { + return 3; + } + if (b >= SeqRange4[0] && b <= SeqRange4[1]) + { + return 4; + } return 0; } diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index 810ca477..ac2d8b0e 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -177,7 +177,9 @@ namespace Newtonsoft.Json.Bson base.Close(); if (CloseOutput && _writer != null) + { _writer.Close(); + } } private void AddParent(BsonToken container) @@ -213,7 +215,9 @@ namespace Newtonsoft.Json.Bson else { if (token.Type != BsonType.Object && token.Type != BsonType.Array) + { 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; @@ -267,9 +271,13 @@ namespace Newtonsoft.Json.Bson { base.WriteValue(value); if (value == null) + { AddValue(null, BsonType.Null); + } else + { AddToken(new BsonString(value, true)); + } } /// @@ -290,7 +298,9 @@ namespace Newtonsoft.Json.Bson public override void WriteValue(uint value) { if (value > int.MaxValue) + { 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); @@ -314,7 +324,9 @@ namespace Newtonsoft.Json.Bson public override void WriteValue(ulong value) { if (value > long.MaxValue) + { 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); @@ -491,7 +503,9 @@ namespace Newtonsoft.Json.Bson ValidationUtils.ArgumentNotNull(value, "value"); if (value.Length != 12) + { throw JsonWriterException.Create(this, "An object id must be 12 bytes", null); + } // hack to update the writer state UpdateScopeWithFinishedValue(); diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs index 516ce8fc..593f53c1 100644 --- a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -72,7 +72,9 @@ namespace Newtonsoft.Json.Converters } #endif if (value is SqlBinary) + { return ((SqlBinary)value).Value; + } throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } @@ -81,7 +83,9 @@ namespace Newtonsoft.Json.Converters private void EnsureReflectionObject(Type t) { if (_reflectionObject == null) + { _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName); + } } #endif @@ -102,7 +106,9 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullable(objectType)) + { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } return null; } @@ -135,7 +141,9 @@ namespace Newtonsoft.Json.Converters #endif if (t == typeof(SqlBinary)) + { return new SqlBinary(data); + } throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType)); } @@ -175,14 +183,19 @@ namespace Newtonsoft.Json.Converters { #if !NET20 if (objectType.AssignableToTypeName(BinaryTypeName)) + { return true; + } #endif if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?)) + { return true; + } return false; } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs b/Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs index 8c5618d5..c0a30ba3 100644 --- a/Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs @@ -67,7 +67,9 @@ namespace Newtonsoft.Json.Converters public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.Bytes) + { throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } byte[] value = (byte[])reader.Value; diff --git a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs index 68fe6800..c373b0c3 100644 --- a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -57,11 +57,15 @@ namespace Newtonsoft.Json.Converters public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) + { return null; + } T value = Create(objectType); if (value == null) + { throw new JsonSerializationException("No object created."); + } serializer.Populate(reader, value); return value; diff --git a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs index adfdef5d..9f9b823d 100644 --- a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -123,4 +123,5 @@ namespace Newtonsoft.Json.Converters } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs index 5779d9ee..6749c131 100644 --- a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -59,7 +59,9 @@ namespace Newtonsoft.Json.Converters object columnValue = row[column]; if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value)) + { continue; + } writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName); serializer.Serialize(writer, columnValue); @@ -215,7 +217,7 @@ namespace Newtonsoft.Json.Converters CheckedRead(reader); if (reader.TokenType == JsonToken.StartObject) { - return typeof (DataTable); // nested datatable + return typeof(DataTable); // nested datatable } Type arrayType = GetColumnDataType(reader); @@ -246,4 +248,5 @@ namespace Newtonsoft.Json.Converters } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/DateTimeConverterBase.cs b/Src/Newtonsoft.Json/Converters/DateTimeConverterBase.cs index a928b13a..5e0ed293 100644 --- a/Src/Newtonsoft.Json/Converters/DateTimeConverterBase.cs +++ b/Src/Newtonsoft.Json/Converters/DateTimeConverterBase.cs @@ -42,10 +42,14 @@ namespace Newtonsoft.Json.Converters public override bool CanConvert(Type objectType) { if (objectType == typeof(DateTime) || objectType == typeof(DateTime?)) + { return true; + } #if !NET20 if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?)) + { return true; + } #endif return false; diff --git a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs index b4a84c23..8876243b 100644 --- a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs @@ -45,7 +45,7 @@ namespace Newtonsoft.Json.Converters /// public class DiscriminatedUnionConverter : JsonConverter { -#region UnionDefinition + #region UnionDefinition internal class Union { public List Cases; @@ -60,7 +60,7 @@ namespace Newtonsoft.Json.Converters public FSharpFunction FieldReader; public FSharpFunction Constructor; } -#endregion + #endregion private const string CasePropertyName = "Case"; private const string FieldsPropertyName = "Fields"; @@ -151,7 +151,9 @@ namespace Newtonsoft.Json.Converters public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) + { return null; + } UnionCase caseInfo = null; string caseName = null; @@ -174,13 +176,17 @@ namespace Newtonsoft.Json.Converters caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName); if (caseInfo == null) + { throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName)); + } } else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase)) { ReadAndAssert(reader); if (reader.TokenType != JsonToken.StartArray) + { throw JsonSerializationException.Create(reader, "Union fields must been an array."); + } fields = (JArray)JToken.ReadFrom(reader); } @@ -193,18 +199,23 @@ namespace Newtonsoft.Json.Converters } if (caseInfo == null) + { throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName)); + } object[] typedFieldValues = new object[caseInfo.Fields.Length]; if (caseInfo.Fields.Length > 0 && fields == null) + { throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName)); + } if (fields != null) { if (caseInfo.Fields.Length != fields.Count) + { throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties definied by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName)); - + } for (int i = 0; i < fields.Count; i++) { @@ -212,7 +223,7 @@ namespace Newtonsoft.Json.Converters PropertyInfo fieldProperty = caseInfo.Fields[i]; typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType, serializer); - } + } } object[] args = { typedFieldValues }; @@ -230,7 +241,9 @@ namespace Newtonsoft.Json.Converters public override bool CanConvert(Type objectType) { if (typeof(IEnumerable).IsAssignableFrom(objectType)) + { return false; + } // all fsharp objects have CompilationMappingAttribute // get the fsharp assembly from the attribute and initialize latebound methods @@ -255,7 +268,9 @@ namespace Newtonsoft.Json.Converters } if (!isFSharpType) + { return false; + } return (bool)FSharpUtils.IsUnion(null, objectType, null); } @@ -263,8 +278,11 @@ namespace Newtonsoft.Json.Converters private static void ReadAndAssert(JsonReader reader) { if (!reader.Read()) + { throw JsonSerializationException.Create(reader, "Unexpected end when reading union."); + } } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index 92a26649..964f727f 100644 --- a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -73,9 +73,13 @@ namespace Newtonsoft.Json.Converters { string valueJson; if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out valueJson)) + { writer.WriteValue(valueJson); + } else + { writer.WriteValue(keyValue); + } } else { @@ -90,13 +94,17 @@ namespace Newtonsoft.Json.Converters ReadAndAssert(reader); if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase)) + { throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + } } private static void ReadAndAssert(JsonReader reader) { if (!reader.Read()) + { throw new JsonSerializationException("Unexpected end."); + } } /// @@ -135,7 +143,9 @@ namespace Newtonsoft.Json.Converters private static void EnsureReflectionObject(Type objectType) { if (_reflectionObject == null) + { _reflectionObject = ReflectionObject.Create(objectType, KeyPropertyName, ValuePropertyName); + } } /// @@ -151,4 +161,5 @@ namespace Newtonsoft.Json.Converters } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs index a1fbfee3..70477752 100644 --- a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs +++ b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs @@ -69,7 +69,9 @@ namespace Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.Comment) { if (!reader.Read()) + { throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); + } } switch (reader.TokenType) @@ -80,7 +82,9 @@ namespace Newtonsoft.Json.Converters return ReadList(reader); default: if (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) + { return reader.Value; + } throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } @@ -121,7 +125,9 @@ namespace Newtonsoft.Json.Converters string propertyName = reader.Value.ToString(); if (!reader.Read()) + { throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); + } object v = ReadValue(reader); diff --git a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs index 79303149..9d2f822a 100644 --- a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs @@ -86,7 +86,9 @@ namespace Newtonsoft.Json.Converters if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) + { dateTime = dateTime.ToUniversalTime(); + } text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); } @@ -96,7 +98,9 @@ namespace Newtonsoft.Json.Converters DateTimeOffset dateTimeOffset = (DateTimeOffset)value; if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal) + { dateTimeOffset = dateTimeOffset.ToUniversalTime(); + } text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture); } @@ -129,7 +133,9 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) + { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } return null; } @@ -138,38 +144,54 @@ namespace Newtonsoft.Json.Converters { #if !NET20 if (t == typeof(DateTimeOffset)) + { return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value); + } // converter is expected to return a DateTime if (reader.Value is DateTimeOffset) + { return ((DateTimeOffset)reader.Value).DateTime; + } #endif return reader.Value; } if (reader.TokenType != JsonToken.String) + { throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } string dateText = reader.Value.ToString(); if (string.IsNullOrEmpty(dateText) && nullable) + { return null; + } #if !NET20 if (t == typeof(DateTimeOffset)) { if (!string.IsNullOrEmpty(_dateTimeFormat)) + { return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); + } else + { return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles); + } } #endif if (!string.IsNullOrEmpty(_dateTimeFormat)) + { return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); + } else + { return DateTime.Parse(dateText, Culture, _dateTimeStyles); + } } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index d6702799..96846728 100644 --- a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -87,18 +87,24 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullable(objectType)) + { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } return null; } if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + { throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); + } reader.Read(); if (reader.TokenType != JsonToken.Integer) + { throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } long ticks = (long)reader.Value; @@ -107,11 +113,15 @@ namespace Newtonsoft.Json.Converters reader.Read(); if (reader.TokenType != JsonToken.EndConstructor) + { throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } #if !NET20 if (t == typeof(DateTimeOffset)) + { return new DateTimeOffset(d); + } #endif return d; diff --git a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index e5b219f0..16c6b72b 100644 --- a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -91,7 +91,9 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!isNullable) + { throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair."); + } return null; } @@ -139,7 +141,9 @@ namespace Newtonsoft.Json.Converters : objectType; if (t.IsValueType() && t.IsGenericType()) + { return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)); + } return false; } @@ -147,7 +151,9 @@ namespace Newtonsoft.Json.Converters private static void ReadAndAssert(JsonReader reader) { if (!reader.Read()) + { throw JsonSerializationException.Create(reader, "Unexpected end when reading KeyValuePair."); + } } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/RegexConverter.cs b/Src/Newtonsoft.Json/Converters/RegexConverter.cs index e5898332..1d6de625 100644 --- a/Src/Newtonsoft.Json/Converters/RegexConverter.cs +++ b/Src/Newtonsoft.Json/Converters/RegexConverter.cs @@ -51,9 +51,13 @@ namespace Newtonsoft.Json.Converters BsonWriter bsonWriter = writer as BsonWriter; if (bsonWriter != null) + { WriteBson(bsonWriter, regex); + } else + { WriteJson(writer, regex, serializer); + } } private bool HasFlag(RegexOptions options, RegexOptions flag) @@ -73,18 +77,26 @@ namespace Newtonsoft.Json.Converters string options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) + { options += "i"; + } if (HasFlag(regex.Options, RegexOptions.Multiline)) + { options += "m"; + } if (HasFlag(regex.Options, RegexOptions.Singleline)) + { options += "s"; + } options += "u"; if (HasFlag(regex.Options, RegexOptions.ExplicitCapture)) + { options += "x"; + } writer.WriteRegex(regex.ToString(), options); } @@ -112,10 +124,14 @@ namespace Newtonsoft.Json.Converters public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject) + { return ReadRegexObject(reader, serializer); + } if (reader.TokenType == JsonToken.String) + { return ReadRegexString(reader); + } throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex."); } @@ -164,20 +180,30 @@ namespace Newtonsoft.Json.Converters string propertyName = reader.Value.ToString(); if (!reader.Read()) + { throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex."); + } if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase)) + { pattern = (string)reader.Value; + } else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase)) + { options = serializer.Deserialize(reader); + } else + { reader.Skip(); + } break; case JsonToken.Comment: break; case JsonToken.EndObject: if (pattern == null) + { throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found."); + } return new Regex(pattern, options ?? RegexOptions.None); } diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index a30304d1..b6cfc963 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -33,6 +33,7 @@ using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Converters @@ -111,7 +112,9 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) + { throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } return null; } @@ -127,7 +130,9 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Integer) { if (!AllowIntegerValues) + { throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value)); + } return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t); } diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 709f4432..65b6e57c 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -41,10 +41,12 @@ using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Converters { + #region XmlNodeWrappers #if !DOTNET && !PORTABLE && !PORTABLE40 internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument @@ -128,7 +130,9 @@ namespace Newtonsoft.Json.Converters get { if (_document.DocumentElement == null) + { return null; + } return new XmlElementWrapper(_document.DocumentElement); } @@ -259,7 +263,9 @@ namespace Newtonsoft.Json.Converters // childnodes is read multiple times // cache results to prevent multiple reads which kills perf in large documents if (_childNodes == null) + { _childNodes = _node.ChildNodes.Cast().Select(WrapNode).ToList(); + } return _childNodes; } @@ -270,11 +276,11 @@ namespace Newtonsoft.Json.Converters switch (node.NodeType) { case XmlNodeType.Element: - return new XmlElementWrapper((XmlElement) node); + return new XmlElementWrapper((XmlElement)node); case XmlNodeType.XmlDeclaration: - return new XmlDeclarationWrapper((XmlDeclaration) node); + return new XmlDeclarationWrapper((XmlDeclaration)node); case XmlNodeType.DocumentType: - return new XmlDocumentTypeWrapper((XmlDocumentType) node); + return new XmlDocumentTypeWrapper((XmlDocumentType)node); default: return new XmlNodeWrapper(node); } @@ -285,7 +291,9 @@ namespace Newtonsoft.Json.Converters get { if (_node.Attributes == null) + { return null; + } return _node.Attributes.Cast().Select(WrapNode).ToList(); } @@ -296,11 +304,13 @@ namespace Newtonsoft.Json.Converters get { XmlNode node = (_node is XmlAttribute) - ? ((XmlAttribute) _node).OwnerElement + ? ((XmlAttribute)_node).OwnerElement : _node.ParentNode; if (node == null) + { return null; + } return WrapNode(node); } @@ -314,7 +324,7 @@ namespace Newtonsoft.Json.Converters public IXmlNode AppendChild(IXmlNode newChild) { - XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper) newChild; + XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper)newChild; _node.AppendChild(xmlNodeWrapper._node); _childNodes = null; @@ -474,7 +484,9 @@ namespace Newtonsoft.Json.Converters IList childNodes = base.ChildNodes; if (Document.Declaration != null && childNodes[0].NodeType != XmlNodeType.XmlDeclaration) + { childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration)); + } return childNodes; } @@ -547,7 +559,9 @@ namespace Newtonsoft.Json.Converters get { if (Document.Root == null) + { return null; + } return new XElementWrapper(Document.Root); } @@ -591,7 +605,9 @@ namespace Newtonsoft.Json.Converters get { if (Text.Parent == null) + { return null; + } return XContainerWrapper.WrapNode(Text.Parent); } @@ -621,7 +637,9 @@ namespace Newtonsoft.Json.Converters get { if (Text.Parent == null) + { return null; + } return XContainerWrapper.WrapNode(Text.Parent); } @@ -673,7 +691,9 @@ namespace Newtonsoft.Json.Converters // childnodes is read multiple times // cache results to prevent multiple reads which kills perf in large documents if (_childNodes == null) + { _childNodes = Container.Nodes().Select(WrapNode).ToList(); + } return _childNodes; } @@ -684,7 +704,9 @@ namespace Newtonsoft.Json.Converters get { if (Container.Parent == null) + { return null; + } return WrapNode(Container.Parent); } @@ -693,23 +715,41 @@ namespace Newtonsoft.Json.Converters internal static IXmlNode WrapNode(XObject node) { if (node is XDocument) + { return new XDocumentWrapper((XDocument)node); + } else if (node is XElement) + { return new XElementWrapper((XElement)node); + } else if (node is XContainer) + { return new XContainerWrapper((XContainer)node); + } else if (node is XProcessingInstruction) + { return new XProcessingInstructionWrapper((XProcessingInstruction)node); + } else if (node is XText) + { return new XTextWrapper((XText)node); + } else if (node is XComment) + { return new XCommentWrapper((XComment)node); + } else if (node is XAttribute) + { return new XAttributeWrapper((XAttribute)node); + } else if (node is XDocumentType) + { return new XDocumentTypeWrapper((XDocumentType)node); + } else + { return new XObjectWrapper(node); + } } public override IXmlNode AppendChild(IXmlNode newChild) @@ -810,7 +850,9 @@ namespace Newtonsoft.Json.Converters get { if (Attribute.Parent == null) + { return null; + } return XContainerWrapper.WrapNode(Attribute.Parent); } @@ -916,23 +958,31 @@ namespace Newtonsoft.Json.Converters PushParentNamespaces(node, manager); if (!OmitRootObject) + { writer.WriteStartObject(); + } SerializeNode(writer, node, manager, !OmitRootObject); if (!OmitRootObject) + { writer.WriteEndObject(); + } } private IXmlNode WrapXml(object value) { #if !NET20 if (value is XObject) + { return XContainerWrapper.WrapNode((XObject)value); + } #endif #if !(DOTNET || PORTABLE) if (value is XmlNode) + { return XmlNodeWrapper.WrapNode((XmlNode)value); + } #endif throw new ArgumentException("Value must be an XML object.", "value"); @@ -948,7 +998,9 @@ namespace Newtonsoft.Json.Converters if (parent.NodeType == XmlNodeType.Element) { if (parentElements == null) + { parentElements = new List(); + } parentElements.Add(parent); } @@ -964,7 +1016,9 @@ namespace Newtonsoft.Json.Converters foreach (IXmlNode attribute in parentElement.Attributes) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") + { manager.AddNamespace(attribute.LocalName, attribute.Value); + } } } } @@ -977,9 +1031,13 @@ namespace Newtonsoft.Json.Converters : manager.LookupPrefix(node.NamespaceUri); if (!string.IsNullOrEmpty(prefix)) + { return prefix + ":" + node.LocalName; + } else + { return node.LocalName; + } } private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager) @@ -988,18 +1046,26 @@ namespace Newtonsoft.Json.Converters { case XmlNodeType.Attribute: if (node.NamespaceUri == JsonNamespaceUri) + { return "$" + node.LocalName; + } else + { return "@" + ResolveFullName(node, manager); + } case XmlNodeType.CDATA: return CDataName; case XmlNodeType.Comment: return CommentName; case XmlNodeType.Element: if (node.NamespaceUri == JsonNamespaceUri) + { return "$" + node.LocalName; + } else + { return ResolveFullName(node, manager); + } case XmlNodeType.ProcessingInstruction: return "?" + ResolveFullName(node, manager); case XmlNodeType.DocumentType: @@ -1071,7 +1137,9 @@ namespace Newtonsoft.Json.Converters string elementNames = nodeNameGroup.Key; if (writePropertyName) + { writer.WritePropertyName(elementNames); + } writer.WriteStartArray(); @@ -1116,7 +1184,9 @@ namespace Newtonsoft.Json.Converters } if (writePropertyName) + { writer.WritePropertyName(GetPropertyName(node, manager)); + } if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text) @@ -1130,9 +1200,13 @@ namespace Newtonsoft.Json.Converters // empty element if (element.IsEmpty) + { writer.WriteNull(); + } else + { writer.WriteValue(string.Empty); + } } else { @@ -1154,7 +1228,9 @@ namespace Newtonsoft.Json.Converters break; case XmlNodeType.Comment: if (writePropertyName) + { writer.WriteComment(node.Value); + } break; case XmlNodeType.Attribute: case XmlNodeType.Text: @@ -1163,16 +1239,22 @@ namespace Newtonsoft.Json.Converters case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri) + { return; + } if (node.NamespaceUri == JsonNamespaceUri) { if (node.LocalName == "Array") + { return; + } } if (writePropertyName) + { writer.WritePropertyName(GetPropertyName(node, manager)); + } writer.WriteValue(node.Value); break; case XmlNodeType.XmlDeclaration: @@ -1244,7 +1326,9 @@ namespace Newtonsoft.Json.Converters public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) + { return null; + } XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); IXmlDocument document = null; @@ -1254,7 +1338,9 @@ namespace Newtonsoft.Json.Converters if (typeof(XObject).IsAssignableFrom(objectType)) { if (objectType != typeof(XDocument) && objectType != typeof(XElement)) + { throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement."); + } XDocument d = new XDocument(); document = new XDocumentWrapper(d); @@ -1265,7 +1351,9 @@ namespace Newtonsoft.Json.Converters if (typeof(XmlNode).IsAssignableFrom(objectType)) { if (objectType != typeof(XmlDocument)) + { throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments"); + } XmlDocument d = new XmlDocument(); // prevent http request when resolving any DTD references @@ -1277,10 +1365,14 @@ namespace Newtonsoft.Json.Converters #endif if (document == null || rootNode == null) + { throw new JsonSerializationException("Unexpected type when converting XML: " + objectType); + } if (reader.TokenType != JsonToken.StartObject) + { throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object."); + } if (!string.IsNullOrEmpty(DeserializeRootElementName)) { @@ -1353,7 +1445,9 @@ namespace Newtonsoft.Json.Converters private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { if (string.IsNullOrEmpty(propertyName)) + { throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML."); + } Dictionary attributeNameValues = ReadAttributeElements(reader, manager); @@ -1443,7 +1537,7 @@ namespace Newtonsoft.Json.Converters ? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(attributeName, attributeValue); - ((IXmlElement) currentNode).SetAttributeNode(attribute); + ((IXmlElement)currentNode).SetAttributeNode(attribute); } private string ConvertTokenToXmlValue(JsonReader reader) @@ -1456,7 +1550,9 @@ namespace Newtonsoft.Json.Converters { #if !(NET20 || NET35 || PORTABLE || PORTABLE40) if (reader.Value is BigInteger) + { return ((BigInteger)reader.Value).ToString(CultureInfo.InvariantCulture); + } #endif return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); @@ -1464,10 +1560,14 @@ namespace Newtonsoft.Json.Converters else if (reader.TokenType == JsonToken.Float) { if (reader.Value is decimal) + { return XmlConvert.ToString((decimal)reader.Value); + } if (reader.Value is float) + { return XmlConvert.ToString((float)reader.Value); - + } + return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); } else if (reader.TokenType == JsonToken.Boolean) @@ -1478,7 +1578,9 @@ namespace Newtonsoft.Json.Converters { #if !NET20 if (reader.Value is DateTimeOffset) + { return XmlConvert.ToString((DateTimeOffset)reader.Value); + } #endif DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture); @@ -1735,7 +1837,9 @@ namespace Newtonsoft.Json.Converters { case JsonToken.PropertyName: if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null) + { throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName."); + } string propertyName = reader.Value.ToString(); reader.Read(); @@ -1769,7 +1873,7 @@ namespace Newtonsoft.Json.Converters } break; case JsonToken.Comment: - currentNode.AppendChild(document.CreateComment((string) reader.Value)); + currentNode.AppendChild(document.CreateComment((string)reader.Value)); break; case JsonToken.EndObject: case JsonToken.EndArray: @@ -1810,7 +1914,6 @@ namespace Newtonsoft.Json.Converters { return c.Where(a => a.NamespaceUri != JsonNamespaceUri); } - #endregion /// @@ -1823,12 +1926,16 @@ namespace Newtonsoft.Json.Converters public override bool CanConvert(Type valueType) { #if !NET20 - if (typeof (XObject).IsAssignableFrom(valueType)) + if (typeof(XObject).IsAssignableFrom(valueType)) + { return true; + } #endif #if !(DOTNET || PORTABLE) - if (typeof (XmlNode).IsAssignableFrom(valueType)) + if (typeof(XmlNode).IsAssignableFrom(valueType)) + { return true; + } #endif return false; @@ -1836,4 +1943,4 @@ namespace Newtonsoft.Json.Converters } } -#endif +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/DefaultValueHandling.cs b/Src/Newtonsoft.Json/DefaultValueHandling.cs index 6125e920..a63adf94 100644 --- a/Src/Newtonsoft.Json/DefaultValueHandling.cs +++ b/Src/Newtonsoft.Json/DefaultValueHandling.cs @@ -64,4 +64,4 @@ namespace Newtonsoft.Json /// IgnoreAndPopulate = Ignore | Populate } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonContainerAttribute.cs b/Src/Newtonsoft.Json/JsonContainerAttribute.cs index de777392..cfc1b58f 100644 --- a/Src/Newtonsoft.Json/JsonContainerAttribute.cs +++ b/Src/Newtonsoft.Json/JsonContainerAttribute.cs @@ -66,7 +66,7 @@ namespace Newtonsoft.Json /// /// [JsonContainer(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// - public object[] ItemConverterParameters { get; set; } + public object[] ItemConverterParameters { get; set; } // yuck. can't set nullable properties on an attribute in C# // have to use this approach to get an unset default state diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs index fdb0deb3..a2a89cec 100644 --- a/Src/Newtonsoft.Json/JsonConvert.cs +++ b/Src/Newtonsoft.Json/JsonConvert.cs @@ -40,6 +40,7 @@ using Newtonsoft.Json.Serialization; using System.Text; #if !(NET20 || PORTABLE40) using System.Xml.Linq; + #endif namespace Newtonsoft.Json @@ -273,10 +274,14 @@ namespace Newtonsoft.Json private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || !(double.IsInfinity(value) || double.IsNaN(value))) + { return text; + } if (floatFormatHandling == FloatFormatHandling.DefaultValue) + { return (!nullable) ? "0.0" : Null; + } return quoteChar + text + quoteChar; } @@ -299,7 +304,9 @@ namespace Newtonsoft.Json private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) + { return text; + } return text + ".0"; } @@ -307,7 +314,9 @@ namespace Newtonsoft.Json private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) + { return text; + } return text + ".0"; } @@ -391,7 +400,9 @@ namespace Newtonsoft.Json public static string ToString(Uri value) { if (value == null) + { return Null; + } return ToString(value, '"'); } @@ -432,7 +443,9 @@ namespace Newtonsoft.Json public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') + { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); + } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling); } @@ -445,7 +458,9 @@ namespace Newtonsoft.Json public static string ToString(object value) { if (value == null) + { return Null; + } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(value.GetType()); @@ -839,7 +854,9 @@ namespace Newtonsoft.Json // by default DeserializeObject should check for additional content if (!jsonSerializer.IsCheckAdditionalContentSet()) + { jsonSerializer.CheckAdditionalContent = true; + } using (var reader = new JsonTextReader(new StringReader(value))) { @@ -945,7 +962,9 @@ namespace Newtonsoft.Json jsonSerializer.Populate(jsonReader, target); if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) + { throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); + } } } @@ -1127,4 +1146,4 @@ namespace Newtonsoft.Json } #endif } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonConverterAttribute.cs b/Src/Newtonsoft.Json/JsonConverterAttribute.cs index 1b759c90..42891923 100644 --- a/Src/Newtonsoft.Json/JsonConverterAttribute.cs +++ b/Src/Newtonsoft.Json/JsonConverterAttribute.cs @@ -59,7 +59,9 @@ namespace Newtonsoft.Json public JsonConverterAttribute(Type converterType) { if (converterType == null) + { throw new ArgumentNullException("converterType"); + } _converterType = converterType; } @@ -70,7 +72,7 @@ namespace Newtonsoft.Json /// Type of the converter. /// Parameter list to use when constructing the JsonConverter. Can be null. public JsonConverterAttribute(Type converterType, params object[] converterParameters) - : this(converterType) + : this(converterType) { ConverterParameters = converterParameters; } diff --git a/Src/Newtonsoft.Json/JsonPosition.cs b/Src/Newtonsoft.Json/JsonPosition.cs index 57cf04ed..bf6221cc 100644 --- a/Src/Newtonsoft.Json/JsonPosition.cs +++ b/Src/Newtonsoft.Json/JsonPosition.cs @@ -41,7 +41,7 @@ namespace Newtonsoft.Json internal struct JsonPosition { - private static readonly char[] SpecialCharacters = {'.', ' ', '[', ']', '(', ')'}; + private static readonly char[] SpecialCharacters = { '.', ' ', '[', ']', '(', ')' }; internal JsonContainerType Type; internal int Position; @@ -145,7 +145,9 @@ namespace Newtonsoft.Json message = message.Trim(); if (!message.EndsWith('.')) + { message += "."; + } message += " "; } @@ -153,11 +155,13 @@ namespace Newtonsoft.Json 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; } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonPropertyAttribute.cs b/Src/Newtonsoft.Json/JsonPropertyAttribute.cs index 5175f4c1..0b22395f 100644 --- a/Src/Newtonsoft.Json/JsonPropertyAttribute.cs +++ b/Src/Newtonsoft.Json/JsonPropertyAttribute.cs @@ -62,7 +62,7 @@ namespace Newtonsoft.Json /// /// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// - public object[] ItemConverterParameters { get; set; } + public object[] ItemConverterParameters { get; set; } /// /// Gets or sets the null value handling used when serializing this property. diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index 25e58ec7..3e99b5bb 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -242,7 +242,9 @@ namespace Newtonsoft.Json set { if (value <= 0) + { throw new ArgumentException("Value must be positive.", "value"); + } _maxDepth = value; } @@ -300,7 +302,9 @@ namespace Newtonsoft.Json get { if (_currentPosition.Type == JsonContainerType.None) + { return string.Empty; + } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart @@ -471,13 +475,17 @@ namespace Newtonsoft.Json if (t == JsonToken.Date) { if (Value is DateTime) + { SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); + } return (DateTimeOffset)Value; } if (t == JsonToken.Null) + { return null; + } if (t == JsonToken.String) { @@ -500,12 +508,14 @@ namespace Newtonsoft.Json SetToken(JsonToken.Date, dt, false); return dt; } - + throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } if (t == JsonToken.EndArray) + { return null; + } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } @@ -565,7 +575,9 @@ namespace Newtonsoft.Json } if (t == JsonToken.Null) + { return null; + } if (t == JsonToken.Bytes) { @@ -607,7 +619,9 @@ namespace Newtonsoft.Json } if (t == JsonToken.EndArray) + { return null; + } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } @@ -634,13 +648,17 @@ namespace Newtonsoft.Json if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is decimal)) + { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); + } return (decimal)Value; } if (t == JsonToken.Null) + { return null; + } if (t == JsonToken.String) { @@ -664,7 +682,9 @@ namespace Newtonsoft.Json } if (t == JsonToken.EndArray) + { return null; + } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } @@ -691,13 +711,17 @@ namespace Newtonsoft.Json if (t == JsonToken.Integer || t == JsonToken.Float) { if (!(Value is int)) + { SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); + } return (int)Value; } if (t == JsonToken.Null) + { return null; + } int i; if (t == JsonToken.String) @@ -721,7 +745,9 @@ namespace Newtonsoft.Json } if (t == JsonToken.EndArray) + { return null; + } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } @@ -746,10 +772,14 @@ namespace Newtonsoft.Json } while (t == JsonToken.Comment); if (t == JsonToken.String) + { return (string)Value; + } if (t == JsonToken.Null) + { return null; + } if (JsonTokenUtils.IsPrimitiveToken(t)) { @@ -757,9 +787,13 @@ namespace Newtonsoft.Json { string s; if (Value is IFormattable) + { s = ((IFormattable)Value).ToString(null, Culture); + } else + { s = Value.ToString(); + } SetToken(JsonToken.String, s, false); return s; @@ -767,7 +801,9 @@ namespace Newtonsoft.Json } if (t == JsonToken.EndArray) + { return null; + } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } @@ -786,10 +822,14 @@ namespace Newtonsoft.Json } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Date) + { return (DateTime)Value; + } if (TokenType == JsonToken.Null) + { return null; + } if (TokenType == JsonToken.String) { @@ -819,7 +859,9 @@ namespace Newtonsoft.Json } if (TokenType == JsonToken.EndArray) + { return null; + } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } @@ -831,7 +873,9 @@ namespace Newtonsoft.Json if (TokenType == JsonToken.StartObject) { if (!ReadInternal()) + { throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); + } if (Value.ToString() == JsonTypeReflector.TypePropertyName) { @@ -858,7 +902,9 @@ namespace Newtonsoft.Json public void Skip() { if (TokenType == JsonToken.PropertyName) + { Read(); + } if (JsonTokenUtils.IsStartToken(TokenType)) { @@ -939,18 +985,26 @@ namespace Newtonsoft.Json internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) + { _currentState = State.PostValue; + } else + { SetFinished(); + } if (updateIndex) + { UpdateScopeWithFinishedValue(); + } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) + { _currentPosition.Position++; + } } private void ValidateEnd(JsonToken endToken) @@ -958,12 +1012,18 @@ namespace Newtonsoft.Json JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) + { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); + } if (Peek() != JsonContainerType.None) + { _currentState = State.PostValue; + } else + { SetFinished(); + } } /// @@ -995,9 +1055,13 @@ namespace Newtonsoft.Json private void SetFinished() { if (SupportMultipleContent) + { _currentState = State.Start; + } else + { _currentState = State.Finished; + } } private JsonContainerType GetTypeForCloseToken(JsonToken token) @@ -1030,7 +1094,9 @@ namespace Newtonsoft.Json protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) + { Close(); + } } /// diff --git a/Src/Newtonsoft.Json/JsonSerializer.cs b/Src/Newtonsoft.Json/JsonSerializer.cs index 526f61cf..8aa4f63e 100644 --- a/Src/Newtonsoft.Json/JsonSerializer.cs +++ b/Src/Newtonsoft.Json/JsonSerializer.cs @@ -90,7 +90,9 @@ namespace Newtonsoft.Json set { if (value == null) + { throw new ArgumentNullException("value", "Reference resolver cannot be null."); + } _referenceResolver = value; } @@ -105,7 +107,9 @@ namespace Newtonsoft.Json set { if (value == null) + { throw new ArgumentNullException("value", "Serialization binder cannot be null."); + } _binder = value; } @@ -140,7 +144,9 @@ namespace Newtonsoft.Json set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) + { throw new ArgumentOutOfRangeException("value"); + } _typeNameHandling = value; } @@ -156,7 +162,9 @@ namespace Newtonsoft.Json set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) + { throw new ArgumentOutOfRangeException("value"); + } _typeNameAssemblyFormat = value; } @@ -171,7 +179,9 @@ namespace Newtonsoft.Json set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) + { throw new ArgumentOutOfRangeException("value"); + } _preserveReferencesHandling = value; } @@ -186,7 +196,9 @@ namespace Newtonsoft.Json set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) + { throw new ArgumentOutOfRangeException("value"); + } _referenceLoopHandling = value; } @@ -201,7 +213,9 @@ namespace Newtonsoft.Json set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) + { throw new ArgumentOutOfRangeException("value"); + } _missingMemberHandling = value; } @@ -216,7 +230,9 @@ namespace Newtonsoft.Json set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) + { throw new ArgumentOutOfRangeException("value"); + } _nullValueHandling = value; } @@ -231,7 +247,9 @@ namespace Newtonsoft.Json set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) + { throw new ArgumentOutOfRangeException("value"); + } _defaultValueHandling = value; } @@ -247,7 +265,9 @@ namespace Newtonsoft.Json set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) + { throw new ArgumentOutOfRangeException("value"); + } _objectCreationHandling = value; } @@ -263,7 +283,9 @@ namespace Newtonsoft.Json set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) + { throw new ArgumentOutOfRangeException("value"); + } _constructorHandling = value; } @@ -279,7 +301,9 @@ namespace Newtonsoft.Json set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) + { throw new ArgumentOutOfRangeException("value"); + } _metadataPropertyHandling = value; } @@ -294,7 +318,9 @@ namespace Newtonsoft.Json get { if (_converters == null) + { _converters = new JsonConverterCollection(); + } return _converters; } @@ -416,7 +442,9 @@ namespace Newtonsoft.Json set { if (value <= 0) + { throw new ArgumentException("Value must be positive.", "value"); + } _maxDepth = value; _maxDepthSet = true; @@ -492,7 +520,9 @@ namespace Newtonsoft.Json JsonSerializer serializer = Create(); if (settings != null) + { ApplySerializerSettings(serializer, settings); + } return serializer; } @@ -531,7 +561,9 @@ namespace Newtonsoft.Json { JsonSerializer serializer = CreateDefault(); if (settings != null) + { ApplySerializerSettings(serializer, settings); + } return serializer; } @@ -550,67 +582,119 @@ namespace Newtonsoft.Json // serializer specific if (settings._typeNameHandling != null) + { serializer.TypeNameHandling = settings.TypeNameHandling; + } if (settings._metadataPropertyHandling != null) + { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; + } if (settings._typeNameAssemblyFormat != null) + { serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; + } if (settings._preserveReferencesHandling != null) + { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; + } if (settings._referenceLoopHandling != null) + { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; + } if (settings._missingMemberHandling != null) + { serializer.MissingMemberHandling = settings.MissingMemberHandling; + } if (settings._objectCreationHandling != null) + { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; + } if (settings._nullValueHandling != null) + { serializer.NullValueHandling = settings.NullValueHandling; + } if (settings._defaultValueHandling != null) + { serializer.DefaultValueHandling = settings.DefaultValueHandling; + } if (settings._constructorHandling != null) + { serializer.ConstructorHandling = settings.ConstructorHandling; + } if (settings._context != null) + { serializer.Context = settings.Context; + } if (settings._checkAdditionalContent != null) + { serializer._checkAdditionalContent = settings._checkAdditionalContent; + } if (settings.Error != null) + { serializer.Error += settings.Error; + } if (settings.ContractResolver != null) + { serializer.ContractResolver = settings.ContractResolver; + } if (settings.ReferenceResolverProvider != null) + { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); + } if (settings.TraceWriter != null) + { serializer.TraceWriter = settings.TraceWriter; + } if (settings.EqualityComparer != null) + { serializer.EqualityComparer = settings.EqualityComparer; + } if (settings.Binder != null) + { serializer.Binder = settings.Binder; + } // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) + { serializer._formatting = settings._formatting; + } if (settings._dateFormatHandling != null) + { serializer._dateFormatHandling = settings._dateFormatHandling; + } if (settings._dateTimeZoneHandling != null) + { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; + } if (settings._dateParseHandling != null) + { serializer._dateParseHandling = settings._dateParseHandling; + } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) + { serializer._floatFormatHandling = settings._floatFormatHandling; + } if (settings._floatParseHandling != null) + { serializer._floatParseHandling = settings._floatParseHandling; + } if (settings._stringEscapeHandling != null) + { serializer._stringEscapeHandling = settings._stringEscapeHandling; + } if (settings._culture != null) + { serializer._culture = settings._culture; + } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; @@ -660,7 +744,9 @@ namespace Newtonsoft.Json serializerReader.Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) + { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } @@ -732,7 +818,9 @@ namespace Newtonsoft.Json object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) + { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); @@ -806,7 +894,9 @@ namespace Newtonsoft.Json { DefaultContractResolver resolver = _contractResolver as DefaultContractResolver; if (resolver != null) + { textReader.NameTable = resolver.GetState().NameTable; + } } } @@ -814,21 +904,35 @@ namespace Newtonsoft.Json { // reset reader back to previous options if (previousCulture != null) + { reader.Culture = previousCulture; + } if (previousDateTimeZoneHandling != null) + { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.Value; + } if (previousDateParseHandling != null) + { reader.DateParseHandling = previousDateParseHandling.Value; + } if (previousFloatParseHandling != null) + { reader.FloatParseHandling = previousFloatParseHandling.Value; + } if (_maxDepthSet) + { reader.MaxDepth = previousMaxDepth; + } if (_dateFormatStringSet) + { reader.DateFormatString = previousDateFormatString; + } JsonTextReader textReader = reader as JsonTextReader; if (textReader != null) + { textReader.NameTable = null; + } } /// @@ -947,29 +1051,47 @@ namespace Newtonsoft.Json serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) + { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); + } // reset writer back to previous options if (previousFormatting != null) + { jsonWriter.Formatting = previousFormatting.Value; + } if (previousDateFormatHandling != null) + { jsonWriter.DateFormatHandling = previousDateFormatHandling.Value; + } if (previousDateTimeZoneHandling != null) + { jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.Value; + } if (previousFloatFormatHandling != null) + { jsonWriter.FloatFormatHandling = previousFloatFormatHandling.Value; + } if (previousStringEscapeHandling != null) + { jsonWriter.StringEscapeHandling = previousStringEscapeHandling.Value; + } if (_dateFormatStringSet) + { jsonWriter.DateFormatString = previousDateFormatString; + } if (previousCulture != null) + { jsonWriter.Culture = previousCulture; + } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) + { _referenceResolver = new DefaultReferenceResolver(); + } return _referenceResolver; } @@ -992,7 +1114,9 @@ namespace Newtonsoft.Json JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) + { return converter; + } } } @@ -1003,7 +1127,9 @@ namespace Newtonsoft.Json { EventHandler error = Error; if (error != null) + { error(this, e); + } } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonSerializerSettings.cs b/Src/Newtonsoft.Json/JsonSerializerSettings.cs index cc18cb9e..e9cc00cc 100644 --- a/Src/Newtonsoft.Json/JsonSerializerSettings.cs +++ b/Src/Newtonsoft.Json/JsonSerializerSettings.cs @@ -286,7 +286,9 @@ namespace Newtonsoft.Json set { if (value <= 0) + { throw new ArgumentException("Value must be positive.", "value"); + } _maxDepth = value; _maxDepthSet = true; diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index 460a0008..d0c4fb1f 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -201,7 +201,6 @@ namespace Newtonsoft.Json } } - private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { const int charByteCount = 2; @@ -452,7 +451,9 @@ namespace Newtonsoft.Json // returns true if it hits // end of object or array if (ParsePostValue()) + { return true; + } break; case State.Finished: if (EnsureChars(0, false)) @@ -467,7 +468,7 @@ namespace Newtonsoft.Json ParseComment(); return true; } - + throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } return false; @@ -750,7 +751,7 @@ namespace Newtonsoft.Json { return; } - + throw JsonReaderException.Create(this, "Unexpected character encountered while parsing number: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } @@ -959,7 +960,9 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) + { throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); + } break; } @@ -997,7 +1000,9 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(false) == 0) + { return false; + } } else { @@ -1408,7 +1413,7 @@ namespace Newtonsoft.Json { throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString())); } - + numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture); numberType = JsonToken.Integer; #else @@ -1473,7 +1478,9 @@ namespace Newtonsoft.Json _charPos++; if (!EnsureChars(1, false)) + { throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); + } bool singlelineComment; diff --git a/Src/Newtonsoft.Json/JsonTextWriter.cs b/Src/Newtonsoft.Json/JsonTextWriter.cs index 17b5da40..6e5b634f 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.cs @@ -57,7 +57,9 @@ namespace Newtonsoft.Json get { if (_base64Encoder == null) + { _base64Encoder = new Base64Encoder(_writer); + } return _base64Encoder; } @@ -89,7 +91,9 @@ namespace Newtonsoft.Json set { if (value < 0) + { throw new ArgumentException("Indentation value must be greater than 0."); + } _indentation = value; } @@ -104,7 +108,9 @@ namespace Newtonsoft.Json set { if (value != '"' && value != '\'') + { throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); + } _quoteChar = value; UpdateCharEscapeFlags(); @@ -143,7 +149,9 @@ namespace Newtonsoft.Json public JsonTextWriter(TextWriter textWriter) { if (textWriter == null) + { throw new ArgumentNullException("textWriter"); + } _writer = textWriter; _quoteChar = '"'; @@ -265,12 +273,16 @@ namespace Newtonsoft.Json else { if (_quoteName) + { _writer.Write(_quoteChar); + } _writer.Write(name); if (_quoteName) + { _writer.Write(_quoteChar); + } } _writer.Write(':'); @@ -299,7 +311,9 @@ namespace Newtonsoft.Json if (currentIndentCount > 0) { if (_indentChars == null) + { _indentChars = new string(_indentChar, 10).ToCharArray(); + } while (currentIndentCount > 0) { @@ -392,9 +406,13 @@ namespace Newtonsoft.Json InternalWriteValue(JsonToken.String); if (value == null) + { WriteValueInternal(JsonConvert.Null, JsonToken.Null); + } else + { WriteEscapedString(value, true); + } } private void WriteEscapedString(string value, bool quote) @@ -751,7 +769,9 @@ namespace Newtonsoft.Json ulong uvalue = (value < 0) ? (ulong)-value : (ulong)value; if (value < 0) + { _writer.Write('-'); + } WriteIntegerValue(uvalue); } diff --git a/Src/Newtonsoft.Json/JsonValidatingReader.cs b/Src/Newtonsoft.Json/JsonValidatingReader.cs index 17d04370..92053911 100644 --- a/Src/Newtonsoft.Json/JsonValidatingReader.cs +++ b/Src/Newtonsoft.Json/JsonValidatingReader.cs @@ -38,6 +38,7 @@ using System.IO; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json @@ -97,7 +98,9 @@ namespace Newtonsoft.Json private IEnumerable GetRequiredProperties(JsonSchemaModel schema) { if (schema == null || schema.Properties == null) + { return Enumerable.Empty(); + } return schema.Properties.Where(p => p.Value.Required).Select(p => p.Key); } @@ -196,10 +199,14 @@ namespace Newtonsoft.Json get { if (_currentScope == null) + { return new List(new[] { _model }); + } if (_currentScope.Schemas == null || _currentScope.Schemas.Count == 0) + { return EmptySchemaList; + } switch (_currentScope.TokenType) { @@ -208,7 +215,9 @@ namespace Newtonsoft.Json case JTokenType.Object: { if (_currentScope.CurrentPropertyName == null) + { throw new JsonReaderException("CurrentPropertyName has not been set on scope."); + } IList schemas = new List(); @@ -231,7 +240,9 @@ namespace Newtonsoft.Json } if (schemas.Count == 0 && schema.AllowAdditionalProperties && schema.AdditionalProperties != null) + { schemas.Add(schema.AdditionalProperties); + } } return schemas; @@ -245,18 +256,24 @@ namespace Newtonsoft.Json if (!schema.PositionalItemsValidation) { if (schema.Items != null && schema.Items.Count > 0) + { schemas.Add(schema.Items[0]); + } } else { if (schema.Items != null && schema.Items.Count > 0) { if (schema.Items.Count > (_currentScope.ArrayItemCount - 1)) + { schemas.Add(schema.Items[_currentScope.ArrayItemCount - 1]); + } } if (schema.AllowAdditionalItems && schema.AdditionalItems != null) + { schemas.Add(schema.AdditionalItems); + } } } @@ -285,9 +302,13 @@ namespace Newtonsoft.Json { ValidationEventHandler handler = ValidationEventHandler; if (handler != null) + { handler(this, new ValidationEventArgs(exception)); + } else + { throw exception; + } } /// @@ -312,7 +333,9 @@ namespace Newtonsoft.Json set { if (TokenType != JsonToken.None) + { throw new InvalidOperationException("Cannot change schema while validating JSON."); + } _schema = value; _model = null; @@ -331,13 +354,17 @@ namespace Newtonsoft.Json private void ValidateNotDisallowed(JsonSchemaModel schema) { if (schema == null) + { return; + } JsonSchemaType? currentNodeType = GetCurrentNodeSchemaType(); if (currentNodeType != null) { if (JsonSchemaGenerator.HasFlag(schema.Disallow, currentNodeType.Value)) + { RaiseError("Type {0} is disallowed.".FormatWith(CultureInfo.InvariantCulture, currentNodeType), schema); + } } } @@ -449,10 +476,14 @@ namespace Newtonsoft.Json public override bool Read() { if (!_reader.Read()) + { return false; + } if (_reader.TokenType == JsonToken.Comment) + { return true; + } ValidateCurrentToken(); return true; @@ -467,7 +498,9 @@ namespace Newtonsoft.Json _model = builder.Build(_schema); if (!JsonTokenUtils.IsStartToken(_reader.TokenType)) + { Push(new SchemaScope(JTokenType.None, CurrentMemberSchemas)); + } } switch (_reader.TokenType) @@ -584,7 +617,9 @@ namespace Newtonsoft.Json if (schemaScope.CurrentItemWriter == null) { if (JsonTokenUtils.IsEndToken(_reader.TokenType)) + { continue; + } schemaScope.CurrentItemWriter = new JTokenWriter(); } @@ -602,7 +637,9 @@ namespace Newtonsoft.Json if (isInUniqueArray) { if (schemaScope.UniqueArrayItems.Contains(finishedItem, JToken.EqualityComparer)) + { RaiseError("Non-unique array item at index {0}.".FormatWith(CultureInfo.InvariantCulture, schemaScope.ArrayItemCount - 1), schemaScope.Schemas.First(s => s.UniqueItems)); + } schemaScope.UniqueArrayItems.Add(finishedItem); } @@ -630,7 +667,9 @@ namespace Newtonsoft.Json private void ValidateEndObject(JsonSchemaModel schema) { if (schema == null) + { return; + } Dictionary requiredProperties = _currentScope.RequiredProperties; @@ -640,31 +679,43 @@ namespace Newtonsoft.Json requiredProperties.Where(kv => !kv.Value).Select(kv => kv.Key).ToList(); if (unmatchedRequiredProperties.Count > 0) + { RaiseError("Required properties are missing from object: {0}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", unmatchedRequiredProperties.ToArray())), schema); + } } } private void ValidateEndArray(JsonSchemaModel schema) { if (schema == null) + { return; + } int arrayItemCount = _currentScope.ArrayItemCount; if (schema.MaximumItems != null && arrayItemCount > schema.MaximumItems) + { RaiseError("Array item count {0} exceeds maximum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MaximumItems), schema); + } if (schema.MinimumItems != null && arrayItemCount < schema.MinimumItems) + { RaiseError("Array item count {0} is less than minimum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MinimumItems), schema); + } } private void ValidateNull(JsonSchemaModel schema) { if (schema == null) + { return; + } if (!TestType(schema, JsonSchemaType.Null)) + { return; + } ValidateNotDisallowed(schema); } @@ -672,10 +723,14 @@ namespace Newtonsoft.Json private void ValidateBoolean(JsonSchemaModel schema) { if (schema == null) + { return; + } if (!TestType(schema, JsonSchemaType.Boolean)) + { return; + } ValidateNotDisallowed(schema); } @@ -683,27 +738,37 @@ namespace Newtonsoft.Json private void ValidateString(JsonSchemaModel schema) { if (schema == null) + { return; + } if (!TestType(schema, JsonSchemaType.String)) + { return; + } ValidateNotDisallowed(schema); string value = _reader.Value.ToString(); if (schema.MaximumLength != null && value.Length > schema.MaximumLength) + { RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), schema); + } if (schema.MinimumLength != null && value.Length < schema.MinimumLength) + { RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), schema); + } if (schema.Patterns != null) { foreach (string pattern in schema.Patterns) { if (!Regex.IsMatch(value, pattern)) + { RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, pattern), schema); + } } } } @@ -711,10 +776,14 @@ namespace Newtonsoft.Json private void ValidateInteger(JsonSchemaModel schema) { if (schema == null) + { return; + } if (!TestType(schema, JsonSchemaType.Integer)) + { return; + } ValidateNotDisallowed(schema); @@ -723,17 +792,25 @@ namespace Newtonsoft.Json if (schema.Maximum != null) { if (JValue.Compare(JTokenType.Integer, value, schema.Maximum) > 0) + { RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); + } if (schema.ExclusiveMaximum && JValue.Compare(JTokenType.Integer, value, schema.Maximum) == 0) + { RaiseError("Integer {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); + } } if (schema.Minimum != null) { if (JValue.Compare(JTokenType.Integer, value, schema.Minimum) < 0) + { RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); + } if (schema.ExclusiveMinimum && JValue.Compare(JTokenType.Integer, value, schema.Minimum) == 0) + { RaiseError("Integer {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); + } } if (schema.DivisibleBy != null) @@ -747,16 +824,24 @@ namespace Newtonsoft.Json BigInteger i = (BigInteger)value; bool divisibleNonInteger = !Math.Abs(schema.DivisibleBy.Value - Math.Truncate(schema.DivisibleBy.Value)).Equals(0); if (divisibleNonInteger) + { notDivisible = i != 0; + } else + { notDivisible = i % new BigInteger(schema.DivisibleBy.Value) != 0; + } } else #endif + { notDivisible = !IsZero(Convert.ToInt64(value, CultureInfo.InvariantCulture) % schema.DivisibleBy.Value); + } if (notDivisible) + { RaiseError("Integer {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); + } } } @@ -783,10 +868,14 @@ namespace Newtonsoft.Json private void ValidateFloat(JsonSchemaModel schema) { if (schema == null) + { return; + } if (!TestType(schema, JsonSchemaType.Float)) + { return; + } ValidateNotDisallowed(schema); @@ -795,17 +884,25 @@ namespace Newtonsoft.Json if (schema.Maximum != null) { if (value > schema.Maximum) + { RaiseError("Float {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema); + } if (schema.ExclusiveMaximum && value == schema.Maximum) + { RaiseError("Float {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema); + } } if (schema.Minimum != null) { if (value < schema.Minimum) + { RaiseError("Float {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema); + } if (schema.ExclusiveMinimum && value == schema.Minimum) + { RaiseError("Float {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema); + } } if (schema.DivisibleBy != null) @@ -813,7 +910,9 @@ namespace Newtonsoft.Json double remainder = FloatingPointRemainder(value, schema.DivisibleBy.Value); if (!IsZero(remainder)) + { RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); + } } } @@ -832,19 +931,25 @@ namespace Newtonsoft.Json private void ValidatePropertyName(JsonSchemaModel schema) { if (schema == null) + { return; + } string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); if (_currentScope.RequiredProperties.ContainsKey(propertyName)) + { _currentScope.RequiredProperties[propertyName] = true; + } if (!schema.AllowAdditionalProperties) { bool propertyDefinied = IsPropertyDefinied(schema, propertyName); if (!propertyDefinied) + { RaiseError("Property '{0}' has not been defined and the schema does not allow additional properties.".FormatWith(CultureInfo.InvariantCulture, propertyName), schema); + } } _currentScope.CurrentPropertyName = propertyName; @@ -853,14 +958,18 @@ namespace Newtonsoft.Json private bool IsPropertyDefinied(JsonSchemaModel schema, string propertyName) { if (schema.Properties != null && schema.Properties.ContainsKey(propertyName)) + { return true; + } if (schema.PatternProperties != null) { foreach (string pattern in schema.PatternProperties.Keys) { if (Regex.IsMatch(propertyName, pattern)) + { return true; + } } } @@ -870,7 +979,9 @@ namespace Newtonsoft.Json private bool ValidateArray(JsonSchemaModel schema) { if (schema == null) + { return true; + } return (TestType(schema, JsonSchemaType.Array)); } @@ -878,7 +989,9 @@ namespace Newtonsoft.Json private bool ValidateObject(JsonSchemaModel schema) { if (schema == null) + { return true; + } return (TestType(schema, JsonSchemaType.Object)); } diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index 1d0e1365..f84af7fc 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -66,14 +66,14 @@ namespace Newtonsoft.Json { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // - /* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, - /* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, - /* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, - /* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, - /* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, - /* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, - /* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, - /* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error } + /* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, + /* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, + /* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, + /* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, + /* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, + /* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, + /* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, + /* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error } }; internal static State[][] BuildStateArray() @@ -207,7 +207,7 @@ namespace Newtonsoft.Json && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); - JsonPosition? current = insideContainer ? (JsonPosition?) _currentPosition : null; + JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } @@ -346,7 +346,9 @@ namespace Newtonsoft.Json internal void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) + { _currentPosition.Position++; + } } private void Push(JsonContainerType value) @@ -523,11 +525,17 @@ namespace Newtonsoft.Json int initialDepth; if (reader.TokenType == JsonToken.None) + { initialDepth = -1; + } else if (!JsonTokenUtils.IsStartToken(reader.TokenType)) + { initialDepth = reader.Depth + 1; + } else + { initialDepth = reader.Depth; + } WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate, writeComments); } @@ -595,13 +603,21 @@ namespace Newtonsoft.Json case JsonToken.Float: ValidationUtils.ArgumentNotNull(value, "value"); if (value is decimal) + { WriteValue((decimal)value); + } else if (value is double) + { WriteValue((double)value); + } else if (value is float) + { WriteValue((float)value); + } else + { WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture)); + } break; case JsonToken.String: ValidationUtils.ArgumentNotNull(value, "value"); @@ -630,10 +646,14 @@ namespace Newtonsoft.Json ValidationUtils.ArgumentNotNull(value, "value"); #if !NET20 if (value is DateTimeOffset) + { WriteValue((DateTimeOffset)value); + } else #endif + { WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture)); + } break; case JsonToken.Raw: WriteRawValue((value != null) ? value.ToString() : null); @@ -641,9 +661,13 @@ namespace Newtonsoft.Json case JsonToken.Bytes: ValidationUtils.ArgumentNotNull(value, "value"); if (value is Guid) + { WriteValue((Guid)value); + } else + { WriteValue((byte[])value); + } break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", tokenType, "Unexpected token type."); @@ -653,17 +677,25 @@ namespace Newtonsoft.Json private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) + { throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); + } if (reader.TokenType != JsonToken.Integer) + { throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); + } long ticks = (long)reader.Value; DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) + { throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); + } if (reader.TokenType != JsonToken.EndConstructor) + { throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null); + } WriteValue(date); } @@ -734,19 +766,25 @@ namespace Newtonsoft.Json } if (levelsToComplete == 0) + { throw JsonWriterException.Create(this, "No token to close.", null); + } for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState == State.Property) + { WriteNull(); + } if (_formatting == Formatting.Indented) { if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) + { WriteIndent(); + } } WriteEnd(token); @@ -808,7 +846,9 @@ namespace Newtonsoft.Json State newState = StateArray[(int)tokenBeingWritten][(int)_currentState]; if (newState == State.Error) + { throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null); + } if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { @@ -818,12 +858,16 @@ namespace Newtonsoft.Json if (_formatting == Formatting.Indented) { if (_currentState == State.Property) + { WriteIndentSpace(); + } // don't indent a property when it is the first token to be written (i.e. at the start) if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart) || (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start)) + { WriteIndent(); + } } _currentState = newState; @@ -1042,9 +1086,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(int? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1055,9 +1103,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(uint? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1067,9 +1119,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(long? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1080,9 +1136,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(ulong? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1092,9 +1152,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(float? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1104,9 +1168,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(double? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1116,9 +1184,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(bool? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1128,9 +1200,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(short? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1141,9 +1217,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(ushort? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1153,9 +1233,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(char? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1165,9 +1249,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(byte? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1178,9 +1266,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(sbyte? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1190,9 +1282,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(decimal? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1202,9 +1298,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(DateTime? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } #if !NET20 @@ -1215,9 +1315,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(DateTimeOffset? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } #endif @@ -1228,9 +1332,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(Guid? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1240,9 +1348,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(TimeSpan? value) { if (value == null) + { WriteNull(); + } else + { WriteValue(value.Value); + } } /// @@ -1252,9 +1364,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(byte[] value) { if (value == null) + { WriteNull(); + } else + { InternalWriteValue(JsonToken.Bytes); + } } /// @@ -1264,9 +1380,13 @@ namespace Newtonsoft.Json public virtual void WriteValue(Uri value) { if (value == null) + { WriteNull(); + } else + { InternalWriteValue(JsonToken.String); + } } /// @@ -1322,7 +1442,9 @@ namespace Newtonsoft.Json private void Dispose(bool disposing) { if (_currentState != State.Closed) + { Close(); + } } internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value) @@ -1509,7 +1631,9 @@ namespace Newtonsoft.Json break; case JsonToken.PropertyName: if (!(value is string)) + { throw new ArgumentException("A name is required when setting property name state.", "value"); + } InternalWritePropertyName((string)value); break; @@ -1576,7 +1700,9 @@ namespace Newtonsoft.Json if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) + { throw JsonWriterException.Create(this, "Only white space characters should be used.", null); + } } } diff --git a/Src/Newtonsoft.Json/Linq/CommentHandling.cs b/Src/Newtonsoft.Json/Linq/CommentHandling.cs index 5e91812c..d178df8e 100644 --- a/Src/Newtonsoft.Json/Linq/CommentHandling.cs +++ b/Src/Newtonsoft.Json/Linq/CommentHandling.cs @@ -9,6 +9,7 @@ /// Ignore comments. /// Ignore = 0, + /// /// Load comments as a with type . /// @@ -24,6 +25,7 @@ /// Ignore line information. /// Ignore = 0, + /// /// Load line information. /// diff --git a/Src/Newtonsoft.Json/Linq/Extensions.cs b/Src/Newtonsoft.Json/Linq/Extensions.cs index 184a1f8f..c26c13a5 100644 --- a/Src/Newtonsoft.Json/Linq/Extensions.cs +++ b/Src/Newtonsoft.Json/Linq/Extensions.cs @@ -173,12 +173,13 @@ namespace Newtonsoft.Json.Linq JToken token = value as JToken; if (token == null) + { throw new ArgumentException("Source value must be a JToken."); + } return token.Convert(); } - internal static IEnumerable Values(this IEnumerable source, object key) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); @@ -203,7 +204,9 @@ namespace Newtonsoft.Json.Linq { JToken value = token[key]; if (value != null) + { yield return value.Convert(); + } } } @@ -251,7 +254,9 @@ namespace Newtonsoft.Json.Linq internal static U Convert(this T token) where T : JToken { if (token == null) + { return default(U); + } if (token is U // don't want to cast JValue to its interfaces, want to get the internal value @@ -264,17 +269,23 @@ namespace Newtonsoft.Json.Linq { JValue value = token as JValue; if (value == null) + { throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T))); + } if (value.Value is U) + { return (U)value.Value; + } Type targetType = typeof(U); if (ReflectionUtils.IsNullableType(targetType)) { if (value.Value == null) + { return default(U); + } targetType = Nullable.GetUnderlyingType(targetType); } @@ -305,11 +316,17 @@ namespace Newtonsoft.Json.Linq public static IJEnumerable AsJEnumerable(this IEnumerable source) where T : JToken { if (source == null) + { return null; + } else if (source is IJEnumerable) + { return (IJEnumerable)source; + } else + { return new JEnumerable(source); + } } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs index 475b7504..e73100d2 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -127,7 +127,9 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader."); + } } while (reader.TokenType == JsonToken.Comment) @@ -136,7 +138,9 @@ namespace Newtonsoft.Json.Linq } if (reader.TokenType != JsonToken.StartArray) + { throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } JArray a = new JArray(); a.SetLineInfo(reader as IJsonLineInfo, settings); @@ -176,7 +180,9 @@ namespace Newtonsoft.Json.Linq JArray a = Load(reader, settings); if (reader.Read() && reader.TokenType != JsonToken.Comment) + { throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); + } return a; } @@ -203,7 +209,9 @@ namespace Newtonsoft.Json.Linq JToken token = FromObjectInternal(o, jsonSerializer); if (token.Type != JTokenType.Array) + { throw new ArgumentException("Object serialized to {0}. JArray instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } return (JArray)token; } @@ -271,7 +279,9 @@ namespace Newtonsoft.Json.Linq ? (IEnumerable)content : null; if (a == null) + { return; + } MergeEnumerableContent(this, a, settings); } diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index 8be66161..74e35ff3 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -52,10 +52,14 @@ namespace Newtonsoft.Json.Linq { JConstructor c = content as JConstructor; if (c == null) + { return; + } if (c.Name != null) + { Name = c.Name; + } MergeEnumerableContent(this, c, settings); } @@ -166,7 +170,9 @@ namespace Newtonsoft.Json.Linq ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) + { throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } return GetItem((int)key); } @@ -175,7 +181,9 @@ namespace Newtonsoft.Json.Linq ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) + { throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } SetItem((int)key, value); } @@ -208,7 +216,9 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); + } } while (reader.TokenType == JsonToken.Comment) @@ -217,7 +227,9 @@ namespace Newtonsoft.Json.Linq } if (reader.TokenType != JsonToken.StartConstructor) + { throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo, settings); diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index 8eb10515..a0bc3928 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -121,7 +121,9 @@ namespace Newtonsoft.Json.Linq { #if !(PORTABLE40) if (_busy) + { throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType())); + } #endif } @@ -139,7 +141,9 @@ namespace Newtonsoft.Json.Linq { AddingNewEventHandler handler = _addingNew; if (handler != null) + { handler(this, e); + } } /// @@ -202,18 +206,24 @@ namespace Newtonsoft.Json.Linq internal bool ContentsEqual(JContainer container) { if (container == this) + { return true; + } IList t1 = ChildrenTokens; IList t2 = container.ChildrenTokens; if (t1.Count != t2.Count) + { return false; + } for (int i = 0; i < t1.Count; i++) { if (!t1[i].DeepEquals(t2[i])) + { return false; + } } return true; @@ -294,7 +304,9 @@ namespace Newtonsoft.Json.Linq internal IEnumerable GetDescendants(bool self) { if (self) + { yield return this; + } foreach (JToken o in ChildrenTokens) { @@ -318,17 +330,23 @@ namespace Newtonsoft.Json.Linq internal JToken EnsureParentToken(JToken item, bool skipParentCheck) { if (item == null) + { return JValue.CreateNull(); + } if (skipParentCheck) + { return item; + } // to avoid a token having multiple parents or creating a recursive loop, create a copy if... // the item already has a parent // the item is being added to itself // the item is being added to the root parent of itself if (item.Parent != null || item == this || (item.HasValues && Root == item)) + { item = item.CloneToken(); + } return item; } @@ -345,7 +363,9 @@ namespace Newtonsoft.Json.Linq public int GetHashCode(JToken obj) { if (obj == null) + { return 0; + } return obj.GetHashCode(); } @@ -361,7 +381,9 @@ namespace Newtonsoft.Json.Linq IList children = ChildrenTokens; if (index > children.Count) + { throw new ArgumentOutOfRangeException("index", "Index must be within the bounds of the List."); + } CheckReentrancy(); @@ -377,21 +399,29 @@ namespace Newtonsoft.Json.Linq item.Previous = previous; if (previous != null) + { previous.Next = item; + } item.Next = next; if (next != null) + { next.Previous = item; + } children.Insert(index, item); #if !(DOTNET || PORTABLE40 || PORTABLE) if (_listChanged != null) + { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index)); + } #endif #if !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) + { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); + } #endif } @@ -400,9 +430,13 @@ namespace Newtonsoft.Json.Linq IList children = ChildrenTokens; if (index < 0) + { throw new ArgumentOutOfRangeException("index", "Index is less than 0."); + } if (index >= children.Count) + { throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count."); + } CheckReentrancy(); @@ -411,9 +445,13 @@ namespace Newtonsoft.Json.Linq JToken next = (index == children.Count - 1) ? null : children[index + 1]; if (previous != null) + { previous.Next = next; + } if (next != null) + { next.Previous = previous; + } item.Parent = null; item.Previous = null; @@ -423,11 +461,15 @@ namespace Newtonsoft.Json.Linq #if !(DOTNET || PORTABLE40 || PORTABLE) if (_listChanged != null) + { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index)); + } #endif #if !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) + { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); + } #endif } @@ -453,14 +495,20 @@ namespace Newtonsoft.Json.Linq IList children = ChildrenTokens; if (index < 0) + { throw new ArgumentOutOfRangeException("index", "Index is less than 0."); + } if (index >= children.Count) + { throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count."); + } JToken existing = children[index]; if (IsTokenUnchanged(existing, item)) + { return; + } CheckReentrancy(); @@ -475,11 +523,15 @@ namespace Newtonsoft.Json.Linq item.Previous = previous; if (previous != null) + { previous.Next = item; + } item.Next = next; if (next != null) + { next.Previous = item; + } children[index] = item; @@ -489,11 +541,15 @@ namespace Newtonsoft.Json.Linq #if !(DOTNET || PORTABLE || PORTABLE40) if (_listChanged != null) + { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index)); + } #endif #if !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) + { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, existing, index)); + } #endif } @@ -514,18 +570,24 @@ namespace Newtonsoft.Json.Linq #if !(DOTNET || PORTABLE40 || PORTABLE) if (_listChanged != null) + { OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); + } #endif #if !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) + { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); + } #endif } internal virtual void ReplaceItem(JToken existing, JToken replacement) { if (existing == null || existing.Parent != this) + { return; + } int index = IndexOfItem(existing); SetItem(index, replacement); @@ -539,13 +601,21 @@ namespace Newtonsoft.Json.Linq internal virtual void CopyItemsTo(Array array, int arrayIndex) { if (array == null) + { throw new ArgumentNullException("array"); + } if (arrayIndex < 0) + { throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); + } if (arrayIndex >= array.Length && arrayIndex != 0) + { throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); + } if (Count > array.Length - arrayIndex) + { throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); + } int index = 0; foreach (JToken token in ChildrenTokens) @@ -562,7 +632,9 @@ namespace Newtonsoft.Json.Linq { // null will get turned into a JValue of type null if (v1.Type == JTokenType.Null && newValue == null) + { return true; + } return v1.Equals(newValue); } @@ -575,7 +647,9 @@ namespace Newtonsoft.Json.Linq ValidationUtils.ArgumentNotNull(o, "o"); if (o.Type == JTokenType.Property) + { throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); + } } /// @@ -625,7 +699,9 @@ namespace Newtonsoft.Json.Linq internal static JToken CreateFromContent(object content) { if (content is JToken) + { return (JToken)content; + } return new JValue(content); } @@ -683,14 +759,18 @@ namespace Newtonsoft.Json.Linq int startDepth = reader.Depth; if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + } ReadContentFrom(reader, options); int endDepth = reader.Depth; if (endDepth > startDepth) + { throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + } } internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) @@ -705,7 +785,9 @@ namespace Newtonsoft.Json.Linq if (parent is JProperty && ((JProperty)parent).Value != null) { if (parent == this) + { return; + } parent = parent.Parent; } @@ -724,7 +806,9 @@ namespace Newtonsoft.Json.Linq case JsonToken.EndArray: if (parent == this) + { return; + } parent = parent.Parent; break; @@ -736,7 +820,9 @@ namespace Newtonsoft.Json.Linq break; case JsonToken.EndObject: if (parent == this) + { return; + } parent = parent.Parent; break; @@ -748,7 +834,9 @@ namespace Newtonsoft.Json.Linq break; case JsonToken.EndConstructor: if (parent == this) + { return; + } parent = parent.Parent; break; @@ -788,9 +876,13 @@ namespace Newtonsoft.Json.Linq // handle multiple properties with the same name in JSON JProperty existingPropertyWithName = parentObject.Property(propertyName); if (existingPropertyWithName == null) + { parent.Add(property); + } else + { existingPropertyWithName.Replace(property); + } parent = property; break; default: @@ -819,7 +911,9 @@ namespace Newtonsoft.Json.Linq { ICustomTypeDescriptor d = First as ICustomTypeDescriptor; if (d != null) + { return d.GetProperties(); + } return null; } @@ -883,10 +977,14 @@ namespace Newtonsoft.Json.Linq private JToken EnsureValue(object value) { if (value == null) + { return null; + } if (value is JToken) + { return (JToken)value; + } throw new ArgumentException("Argument is not a JToken."); } @@ -970,7 +1068,9 @@ namespace Newtonsoft.Json.Linq get { if (_syncRoot == null) + { Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } return _syncRoot; } @@ -989,10 +1089,14 @@ namespace Newtonsoft.Json.Linq OnAddingNew(args); if (args.NewObject == null) + { throw new JsonException("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType())); + } if (!(args.NewObject is JToken)) + { throw new JsonException("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JToken))); + } JToken newItem = (JToken)args.NewObject; Add(newItem); @@ -1130,7 +1234,9 @@ namespace Newtonsoft.Json.Linq { JToken contentValue = CreateFromContent(targetItem); if (contentValue.Type != JTokenType.Null) + { target[i] = contentValue; + } } } } diff --git a/Src/Newtonsoft.Json/Linq/JEnumerable.cs b/Src/Newtonsoft.Json/Linq/JEnumerable.cs index 5cf4fc8e..8e75ed8f 100644 --- a/Src/Newtonsoft.Json/Linq/JEnumerable.cs +++ b/Src/Newtonsoft.Json/Linq/JEnumerable.cs @@ -68,7 +68,9 @@ namespace Newtonsoft.Json.Linq public IEnumerator GetEnumerator() { if (_enumerable == null) + { return Empty.GetEnumerator(); + } return _enumerable.GetEnumerator(); } @@ -93,7 +95,9 @@ namespace Newtonsoft.Json.Linq get { if (_enumerable == null) + { return JEnumerable.Empty; + } return new JEnumerable(_enumerable.Values(key)); } @@ -121,7 +125,9 @@ namespace Newtonsoft.Json.Linq public override bool Equals(object obj) { if (obj is JEnumerable) + { return Equals((JEnumerable)obj); + } return false; } @@ -135,7 +141,9 @@ namespace Newtonsoft.Json.Linq public override int GetHashCode() { if (_enumerable == null) + { return 0; + } return _enumerable.GetHashCode(); } diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index b6ad9ada..2ce3970c 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -41,6 +41,7 @@ using System.Globalization; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Linq @@ -120,7 +121,9 @@ namespace Newtonsoft.Json.Linq { JObject t = node as JObject; if (t == null) + { return false; + } return _properties.Compare(t._properties); } @@ -129,7 +132,9 @@ namespace Newtonsoft.Json.Linq { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) + { return; + } base.InsertItem(index, item, skipParentCheck); } @@ -139,7 +144,9 @@ namespace Newtonsoft.Json.Linq ValidationUtils.ArgumentNotNull(o, "o"); if (o.Type != JTokenType.Property) + { throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); + } JProperty newProperty = (JProperty)o; @@ -148,18 +155,24 @@ namespace Newtonsoft.Json.Linq JProperty existingProperty = (JProperty)existing; if (newProperty.Name == existingProperty.Name) + { return; + } } if (_properties.TryGetValue(newProperty.Name, out existing)) + { throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); + } } internal override void MergeItem(object content, JsonMergeSettings settings) { JObject o = content as JObject; if (o == null) + { return; + } foreach (KeyValuePair contentItem in o) { @@ -175,7 +188,9 @@ namespace Newtonsoft.Json.Linq if (existingContainer == null) { if (contentItem.Value.Type != JTokenType.Null) + { existingProperty.Value = contentItem.Value; + } } else if (existingContainer.Type != contentItem.Value.Type) { @@ -194,11 +209,15 @@ namespace Newtonsoft.Json.Linq OnPropertyChanged(childProperty.Name); #if !(DOTNET || PORTABLE40 || PORTABLE) if (_listChanged != null) + { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); + } #endif #if !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) + { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, childProperty, childProperty, IndexOfItem(childProperty))); + } #endif } @@ -240,7 +259,9 @@ namespace Newtonsoft.Json.Linq public JProperty Property(string name) { if (name == null) + { return null; + } JToken property; _properties.TryGetValue(name, out property); @@ -268,7 +289,9 @@ namespace Newtonsoft.Json.Linq string propertyName = key as string; if (propertyName == null) + { throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } return this[propertyName]; } @@ -278,7 +301,9 @@ namespace Newtonsoft.Json.Linq string propertyName = key as string; if (propertyName == null) + { throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); + } this[propertyName] = value; } @@ -340,7 +365,9 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); + } } while (reader.TokenType == JsonToken.Comment) @@ -391,7 +418,9 @@ namespace Newtonsoft.Json.Linq JObject o = Load(reader, settings); if (reader.Read() && reader.TokenType != JsonToken.Comment) + { throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); + } return o; } @@ -418,7 +447,9 @@ namespace Newtonsoft.Json.Linq JToken token = FromObjectInternal(o, jsonSerializer); if (token != null && token.Type != JTokenType.Object) + { throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } return (JObject)token; } @@ -461,12 +492,16 @@ namespace Newtonsoft.Json.Linq public JToken GetValue(string propertyName, StringComparison comparison) { if (propertyName == null) + { return null; + } // attempt to get value via dictionary first for performance JProperty property = Property(propertyName); if (property != null) + { return property.Value; + } // test above already uses this comparison so no need to repeat if (comparison != StringComparison.Ordinal) @@ -474,7 +509,9 @@ namespace Newtonsoft.Json.Linq foreach (JProperty p in _properties) { if (string.Equals(p.Name, propertyName, comparison)) + { return p.Value; + } } } @@ -527,7 +564,9 @@ namespace Newtonsoft.Json.Linq { JProperty property = Property(propertyName); if (property == null) + { return false; + } property.Remove(); return true; @@ -577,7 +616,9 @@ namespace Newtonsoft.Json.Linq { JProperty property = Property(item.Key); if (property == null) + { return false; + } return (property.Value == item.Value); } @@ -585,13 +626,21 @@ namespace Newtonsoft.Json.Linq void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { if (array == null) + { throw new ArgumentNullException("array"); + } if (arrayIndex < 0) + { throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0."); + } if (arrayIndex >= array.Length && arrayIndex != 0) + { throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); + } if (Count > array.Length - arrayIndex) + { throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); + } int index = 0; foreach (JProperty property in _properties) @@ -609,7 +658,9 @@ namespace Newtonsoft.Json.Linq bool ICollection>.Remove(KeyValuePair item) { if (!((ICollection>)this).Contains(item)) + { return false; + } ((IDictionary)this).Remove(item.Key); return true; @@ -642,7 +693,9 @@ namespace Newtonsoft.Json.Linq protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) + { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } } #if !(PORTABLE40 || PORTABLE || NET20) @@ -653,7 +706,9 @@ namespace Newtonsoft.Json.Linq protected virtual void OnPropertyChanging(string propertyName) { if (PropertyChanging != null) + { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); + } } #endif @@ -835,7 +890,9 @@ namespace Newtonsoft.Json.Linq // this can throw an error if value isn't a valid for a JValue if (v == null) + { v = new JValue(value); + } instance[binder.Name] = v; return true; diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index 26c5bbec..e6f42a87 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -45,7 +45,9 @@ namespace Newtonsoft.Json.Linq public IEnumerator GetEnumerator() { if (_token != null) + { yield return _token; + } } IEnumerator IEnumerable.GetEnumerator() @@ -71,7 +73,9 @@ namespace Newtonsoft.Json.Linq public void CopyTo(JToken[] array, int arrayIndex) { if (_token != null) + { array[arrayIndex] = _token; + } } public bool Remove(JToken item) @@ -102,13 +106,17 @@ namespace Newtonsoft.Json.Linq public void Insert(int index, JToken item) { if (index == 0) + { _token = item; + } } public void RemoveAt(int index) { if (index == 0) + { _token = null; + } } public JToken this[int index] @@ -117,7 +125,9 @@ namespace Newtonsoft.Json.Linq set { if (index == 0) + { _token = value; + } } } } @@ -183,7 +193,9 @@ namespace Newtonsoft.Json.Linq internal override JToken GetItem(int index) { if (index != 0) + { throw new ArgumentOutOfRangeException(); + } return Value; } @@ -191,18 +203,26 @@ namespace Newtonsoft.Json.Linq internal override void SetItem(int index, JToken item) { if (index != 0) + { throw new ArgumentOutOfRangeException(); + } if (IsTokenUnchanged(Value, item)) + { return; + } if (Parent != null) + { ((JObject)Parent).InternalPropertyChanging(this); + } base.SetItem(0, item); if (Parent != null) + { ((JObject)Parent).InternalPropertyChanged(this); + } } internal override bool RemoveItem(JToken item) @@ -219,10 +239,14 @@ namespace Newtonsoft.Json.Linq { // don't add comments to JProperty if (item != null && item.Type == JTokenType.Comment) + { return; + } if (Value != null) + { throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + } base.InsertItem(0, item, false); } @@ -236,10 +260,14 @@ namespace Newtonsoft.Json.Linq { JProperty p = content as JProperty; if (p == null) + { return; + } if (p.Value != null && p.Value.Type != JTokenType.Null) + { Value = p.Value; + } } internal override void ClearItems() @@ -313,9 +341,13 @@ namespace Newtonsoft.Json.Linq JToken value = Value; if (value != null) + { value.WriteTo(writer, converters); + } else + { writer.WriteNull(); + } } internal override int GetDeepHashCode() @@ -345,7 +377,9 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader."); + } } while (reader.TokenType == JsonToken.Comment) @@ -354,7 +388,9 @@ namespace Newtonsoft.Json.Linq } if (reader.TokenType != JsonToken.PropertyName) + { throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo, settings); diff --git a/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs b/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs index 205f4c84..796156d4 100644 --- a/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs +++ b/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs @@ -44,16 +44,22 @@ namespace Newtonsoft.Json.Linq protected void ChangeItemKey(JToken item, string newKey) { if (!ContainsItem(item)) + { throw new ArgumentException("The specified item does not exist in this KeyedCollection."); + } string keyForItem = GetKeyForItem(item); if (!Comparer.Equals(keyForItem, newKey)) { if (newKey != null) + { AddKey(newKey, item); + } if (keyForItem != null) + { RemoveKey(keyForItem); + } } } @@ -62,16 +68,22 @@ namespace Newtonsoft.Json.Linq base.ClearItems(); if (_dictionary != null) + { _dictionary.Clear(); + } } public bool Contains(string key) { if (key == null) + { throw new ArgumentNullException("key"); + } if (_dictionary != null) + { return _dictionary.ContainsKey(key); + } return false; } @@ -79,7 +91,9 @@ namespace Newtonsoft.Json.Linq private bool ContainsItem(JToken item) { if (_dictionary == null) + { return false; + } string key = GetKeyForItem(item); JToken value; @@ -89,7 +103,9 @@ namespace Newtonsoft.Json.Linq private void EnsureDictionary() { if (_dictionary == null) + { _dictionary = new Dictionary(Comparer); + } } private string GetKeyForItem(JToken item) @@ -106,10 +122,14 @@ namespace Newtonsoft.Json.Linq public bool Remove(string key) { if (key == null) + { throw new ArgumentNullException("key"); + } if (_dictionary != null) + { return _dictionary.ContainsKey(key) && Remove(_dictionary[key]); + } return false; } @@ -124,7 +144,9 @@ namespace Newtonsoft.Json.Linq private void RemoveKey(string key) { if (_dictionary != null) + { _dictionary.Remove(key); + } } protected override void SetItem(int index, JToken item) @@ -135,14 +157,18 @@ namespace Newtonsoft.Json.Linq if (Comparer.Equals(keyAtIndex, keyForItem)) { if (_dictionary != null) + { _dictionary[keyForItem] = item; + } } else { AddKey(keyForItem, item); if (keyAtIndex != null) + { RemoveKey(keyAtIndex); + } } base.SetItem(index, item); } @@ -152,10 +178,14 @@ namespace Newtonsoft.Json.Linq get { if (key == null) + { throw new ArgumentNullException("key"); + } if (_dictionary != null) + { return _dictionary[key]; + } throw new KeyNotFoundException(); } @@ -193,7 +223,9 @@ namespace Newtonsoft.Json.Linq public bool Compare(JPropertyKeyedCollection other) { if (this == other) + { return true; + } // dictionaries in JavaScript aren't ordered // ignore order when comparing properties @@ -201,31 +233,45 @@ namespace Newtonsoft.Json.Linq Dictionary d2 = other._dictionary; if (d1 == null && d2 == null) + { return true; + } if (d1 == null) + { return (d2.Count == 0); + } if (d2 == null) + { return (d1.Count == 0); + } if (d1.Count != d2.Count) + { return false; + } foreach (KeyValuePair keyAndProperty in d1) { JToken secondValue; if (!d2.TryGetValue(keyAndProperty.Key, out secondValue)) + { return false; + } JProperty p1 = (JProperty)keyAndProperty.Value; JProperty p2 = (JProperty)secondValue; if (p1.Value == null) + { return (p2.Value == null); + } if (!p1.Value.DeepEquals(p2.Value)) + { return false; + } } return true; diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 769d050a..95be1ff8 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -88,7 +88,9 @@ namespace Newtonsoft.Json.Linq get { if (_equalityComparer == null) + { _equalityComparer = new JTokenEqualityComparer(); + } return _equalityComparer; } @@ -115,7 +117,9 @@ namespace Newtonsoft.Json.Linq { JContainer parent = Parent; if (parent == null) + { return this; + } while (parent.Parent != null) { @@ -182,7 +186,9 @@ namespace Newtonsoft.Json.Linq get { if (Parent == null) + { return string.Empty; + } IList ancestors = AncestorsAndSelf().Reverse().ToList(); @@ -233,7 +239,9 @@ namespace Newtonsoft.Json.Linq public void AddAfterSelf(object content) { if (_parent == null) + { throw new InvalidOperationException("The parent is missing."); + } int index = _parent.IndexOfItem(this); _parent.AddInternal(index + 1, content, false); @@ -246,7 +254,9 @@ namespace Newtonsoft.Json.Linq public void AddBeforeSelf(object content) { if (_parent == null) + { throw new InvalidOperationException("The parent is missing."); + } int index = _parent.IndexOfItem(this); _parent.AddInternal(index, content, false); @@ -285,7 +295,9 @@ namespace Newtonsoft.Json.Linq public IEnumerable AfterSelf() { if (Parent == null) + { yield break; + } for (JToken o = Next; o != null; o = o.Next) { @@ -382,7 +394,9 @@ namespace Newtonsoft.Json.Linq public void Remove() { if (_parent == null) + { throw new InvalidOperationException("The parent is missing."); + } _parent.RemoveItem(this); } @@ -394,7 +408,9 @@ namespace Newtonsoft.Json.Linq public void Replace(JToken value) { if (_parent == null) + { throw new InvalidOperationException("The parent is missing."); + } _parent.ReplaceItem(this, value); } @@ -439,10 +455,14 @@ namespace Newtonsoft.Json.Linq private static JValue EnsureValue(JToken value) { if (value == null) + { throw new ArgumentNullException("value"); + } if (value is JProperty) + { value = ((JProperty)value).Value; + } JValue v = value as JValue; @@ -454,7 +474,9 @@ namespace Newtonsoft.Json.Linq ValidationUtils.ArgumentNotNull(token, "token"); if (token is JProperty) + { token = ((JProperty)token).Value; + } return token.Type.ToString(); } @@ -474,11 +496,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BooleanTypes, false)) + { throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return Convert.ToBoolean((int)(BigInteger)v.Value); + } #endif return Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture); @@ -494,12 +520,18 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, false)) + { throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value is DateTimeOffset) + { return (DateTimeOffset)v.Value; + } if (v.Value is string) + { return DateTimeOffset.Parse((string)v.Value, CultureInfo.InvariantCulture); + } return new DateTimeOffset(Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture)); } #endif @@ -512,15 +544,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator bool?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BooleanTypes, true)) + { throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return Convert.ToBoolean((int)(BigInteger)v.Value); + } #endif return (v.Value != null) ? (bool?)Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture) : null; @@ -535,11 +573,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (long)(BigInteger)v.Value; + } #endif return Convert.ToInt64(v.Value, CultureInfo.InvariantCulture); @@ -553,15 +595,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator DateTime?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, true)) + { throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !NET20 if (v.Value is DateTimeOffset) + { return ((DateTimeOffset)v.Value).DateTime; + } #endif return (v.Value != null) ? (DateTime?)Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture) : null; @@ -576,18 +624,28 @@ namespace Newtonsoft.Json.Linq public static explicit operator DateTimeOffset?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, true)) + { throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value == null) + { return null; + } if (v.Value is DateTimeOffset) + { return (DateTimeOffset?)v.Value; + } if (v.Value is string) + { return DateTimeOffset.Parse((string)v.Value, CultureInfo.InvariantCulture); + } return new DateTimeOffset(Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture)); } #endif @@ -600,15 +658,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator decimal?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (decimal?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (decimal?)Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture) : null; @@ -622,15 +686,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator double?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (double?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (double?)Convert.ToDouble(v.Value, CultureInfo.InvariantCulture) : null; @@ -644,15 +714,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator char?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, CharTypes, true)) + { throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (char?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (char?)Convert.ToChar(v.Value, CultureInfo.InvariantCulture) : null; @@ -667,11 +743,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (int)(BigInteger)v.Value; + } #endif return Convert.ToInt32(v.Value, CultureInfo.InvariantCulture); @@ -686,11 +766,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (short)(BigInteger)v.Value; + } #endif return Convert.ToInt16(v.Value, CultureInfo.InvariantCulture); @@ -706,11 +790,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (ushort)(BigInteger)v.Value; + } #endif return Convert.ToUInt16(v.Value, CultureInfo.InvariantCulture); @@ -726,11 +814,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, CharTypes, false)) + { throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (char)(BigInteger)v.Value; + } #endif return Convert.ToChar(v.Value, CultureInfo.InvariantCulture); @@ -745,11 +837,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (byte)(BigInteger)v.Value; + } #endif return Convert.ToByte(v.Value, CultureInfo.InvariantCulture); @@ -765,11 +861,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (sbyte)(BigInteger)v.Value; + } #endif return Convert.ToSByte(v.Value, CultureInfo.InvariantCulture); @@ -783,15 +883,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator int?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (int?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (int?)Convert.ToInt32(v.Value, CultureInfo.InvariantCulture) : null; @@ -805,15 +911,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator short?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (short?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (short?)Convert.ToInt16(v.Value, CultureInfo.InvariantCulture) : null; @@ -828,15 +940,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator ushort?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (ushort?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (ushort?)Convert.ToUInt16(v.Value, CultureInfo.InvariantCulture) : null; @@ -850,15 +968,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator byte?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (byte?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (byte?)Convert.ToByte(v.Value, CultureInfo.InvariantCulture) : null; @@ -873,15 +997,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator sbyte?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (sbyte?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (sbyte?)Convert.ToSByte(v.Value, CultureInfo.InvariantCulture) : null; @@ -896,11 +1026,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, false)) + { throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !NET20 if (v.Value is DateTimeOffset) + { return ((DateTimeOffset)v.Value).DateTime; + } #endif return Convert.ToDateTime(v.Value, CultureInfo.InvariantCulture); @@ -914,15 +1048,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator long?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (long?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (long?)Convert.ToInt64(v.Value, CultureInfo.InvariantCulture) : null; @@ -936,15 +1076,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator float?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (float?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (float?)Convert.ToSingle(v.Value, CultureInfo.InvariantCulture) : null; @@ -959,11 +1105,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (decimal)(BigInteger)v.Value; + } #endif return Convert.ToDecimal(v.Value, CultureInfo.InvariantCulture); @@ -978,15 +1128,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator uint?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (uint?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (uint?)Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture) : null; @@ -1001,15 +1157,21 @@ namespace Newtonsoft.Json.Linq public static explicit operator ulong?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) + { throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (ulong?)(BigInteger)v.Value; + } #endif return (v.Value != null) ? (ulong?)Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture) : null; @@ -1024,11 +1186,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (double)(BigInteger)v.Value; + } #endif return Convert.ToDouble(v.Value, CultureInfo.InvariantCulture); @@ -1043,11 +1209,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (float)(BigInteger)v.Value; + } #endif return Convert.ToSingle(v.Value, CultureInfo.InvariantCulture); @@ -1061,19 +1231,29 @@ namespace Newtonsoft.Json.Linq public static explicit operator string(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, StringTypes, true)) + { throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value == null) + { return null; + } if (v.Value is byte[]) + { return Convert.ToBase64String((byte[])v.Value); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return ((BigInteger)v.Value).ToString(CultureInfo.InvariantCulture); + } #endif return Convert.ToString(v.Value, CultureInfo.InvariantCulture); @@ -1089,11 +1269,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (uint)(BigInteger)v.Value; + } #endif return Convert.ToUInt32(v.Value, CultureInfo.InvariantCulture); @@ -1109,11 +1293,15 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) + { throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return (ulong)(BigInteger)v.Value; + } #endif return Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture); @@ -1127,21 +1315,31 @@ namespace Newtonsoft.Json.Linq public static explicit operator byte[](JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BytesTypes, false)) + { throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value is string) + { return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (v.Value is BigInteger) + { return ((BigInteger)v.Value).ToByteArray(); + } #endif if (v.Value is byte[]) + { return (byte[])v.Value; + } throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); } @@ -1155,10 +1353,14 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, GuidTypes, false)) + { throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value is byte[]) + { return new Guid((byte[])v.Value); + } return (v.Value is Guid) ? (Guid)v.Value : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); } @@ -1171,17 +1373,25 @@ namespace Newtonsoft.Json.Linq public static explicit operator Guid?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, GuidTypes, true)) + { throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value == null) + { return null; + } if (v.Value is byte[]) + { return new Guid((byte[])v.Value); + } return (v.Value is Guid) ? (Guid)v.Value : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); } @@ -1195,7 +1405,9 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, TimeSpanTypes, false)) + { throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } return (v.Value is TimeSpan) ? (TimeSpan)v.Value : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); } @@ -1208,14 +1420,20 @@ namespace Newtonsoft.Json.Linq public static explicit operator TimeSpan?(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, TimeSpanTypes, true)) + { throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value == null) + { return null; + } return (v.Value is TimeSpan) ? (TimeSpan)v.Value : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); } @@ -1228,14 +1446,20 @@ namespace Newtonsoft.Json.Linq public static explicit operator Uri(JToken value) { if (value == null) + { return null; + } JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, UriTypes, true)) + { throw new ArgumentException("Can not convert {0} to Uri.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value == null) + { return null; + } return (v.Value is Uri) ? (Uri)v.Value : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); } @@ -1245,7 +1469,9 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BigIntegerTypes, false)) + { throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } return ConvertUtils.ToBigInteger(v.Value); } @@ -1254,10 +1480,14 @@ namespace Newtonsoft.Json.Linq { JValue v = EnsureValue(value); if (v == null || !ValidateToken(v, BigIntegerTypes, true)) + { throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); + } if (v.Value == null) + { return null; + } return ConvertUtils.ToBigInteger(v.Value); } @@ -1721,18 +1951,18 @@ namespace Newtonsoft.Json.Linq Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); try { - return Enum.Parse(enumType, (string) this, true); + return Enum.Parse(enumType, (string)this, true); } catch (Exception ex) { - throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string) this, enumType.Name), ex); + throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex); } } if (Type == JTokenType.Integer) { Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); - return Enum.ToObject(enumType, ((JValue) this).Value); + return Enum.ToObject(enumType, ((JValue)this).Value); } } @@ -1883,7 +2113,9 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); + } } while (true) @@ -1913,7 +2145,9 @@ namespace Newtonsoft.Json.Linq if (settings != null && settings.CommentHandling == CommentHandling.Ignore) { if (!reader.Read()) + { throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); + } continue; } @@ -1959,7 +2193,9 @@ namespace Newtonsoft.Json.Linq JToken t = Load(reader, settings); if (reader.Read() && reader.TokenType != JsonToken.Comment) + { throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); + } return t; } @@ -2038,7 +2274,9 @@ namespace Newtonsoft.Json.Linq { LineInfoAnnotation annotation = Annotation(); if (annotation != null) + { return annotation.LineNumber; + } return 0; } @@ -2050,7 +2288,9 @@ namespace Newtonsoft.Json.Linq { LineInfoAnnotation annotation = Annotation(); if (annotation != null) + { return annotation.LinePosition; + } return 0; } @@ -2084,7 +2324,9 @@ namespace Newtonsoft.Json.Linq foreach (JToken t in p.Evaluate(this, errorWhenNoMatch)) { if (token != null) + { throw new JsonException("Path returned multiple tokens."); + } token = t; } @@ -2167,18 +2409,20 @@ namespace Newtonsoft.Json.Linq public void AddAnnotation(object annotation) { if (annotation == null) + { throw new ArgumentNullException("annotation"); + } if (_annotations == null) { - _annotations = (annotation is object[]) ? new [] { annotation } : annotation; + _annotations = (annotation is object[]) ? new[] { annotation } : annotation; } else { object[] annotations = _annotations as object[]; if (annotations == null) { - _annotations = new [] { _annotations, annotation }; + _annotations = new[] { _annotations, annotation }; } else { @@ -2215,11 +2459,15 @@ namespace Newtonsoft.Json.Linq { object annotation = annotations[i]; if (annotation == null) + { break; + } T local = annotation as T; if (local != null) + { return local; + } } } @@ -2234,7 +2482,9 @@ namespace Newtonsoft.Json.Linq public object Annotation(Type type) { if (type == null) + { throw new ArgumentNullException("type"); + } if (_annotations != null) { @@ -2242,7 +2492,9 @@ namespace Newtonsoft.Json.Linq if (annotations == null) { if (type.IsInstanceOfType(_annotations)) + { return _annotations; + } } else { @@ -2250,10 +2502,14 @@ namespace Newtonsoft.Json.Linq { object o = annotations[i]; if (o == null) + { break; + } if (type.IsInstanceOfType(o)) + { return o; + } } } } @@ -2269,7 +2525,9 @@ namespace Newtonsoft.Json.Linq public IEnumerable Annotations() where T : class { if (_annotations == null) + { yield break; + } object[] annotations = _annotations as object[]; if (annotations != null) @@ -2278,18 +2536,24 @@ namespace Newtonsoft.Json.Linq { object o = annotations[i]; if (o == null) + { break; + } T casted = o as T; if (casted != null) + { yield return casted; + } } yield break; } T annotation = _annotations as T; if (annotation == null) + { yield break; + } yield return annotation; } @@ -2302,10 +2566,14 @@ namespace Newtonsoft.Json.Linq public IEnumerable Annotations(Type type) { if (type == null) + { throw new ArgumentNullException("type"); + } if (_annotations == null) + { yield break; + } object[] annotations = _annotations as object[]; if (annotations != null) @@ -2314,16 +2582,22 @@ namespace Newtonsoft.Json.Linq { object o = annotations[i]; if (o == null) + { break; + } if (type.IsInstanceOfType(o)) + { yield return o; + } } yield break; } if (!type.IsInstanceOfType(_annotations)) + { yield break; + } yield return _annotations; } @@ -2340,7 +2614,9 @@ namespace Newtonsoft.Json.Linq if (annotations == null) { if (_annotations is T) + { _annotations = null; + } } else { @@ -2350,10 +2626,14 @@ namespace Newtonsoft.Json.Linq { object obj2 = annotations[index]; if (obj2 == null) + { break; + } if (!(obj2 is T)) + { annotations[keepCount++] = obj2; + } index++; } @@ -2380,7 +2660,9 @@ namespace Newtonsoft.Json.Linq public void RemoveAnnotations(Type type) { if (type == null) + { throw new ArgumentNullException("type"); + } if (_annotations != null) { @@ -2388,7 +2670,9 @@ namespace Newtonsoft.Json.Linq if (annotations == null) { if (type.IsInstanceOfType(_annotations)) + { _annotations = null; + } } else { @@ -2398,10 +2682,14 @@ namespace Newtonsoft.Json.Linq { object o = annotations[index]; if (o == null) + { break; + } if (!type.IsInstanceOfType(o)) + { annotations[keepCount++] = o; + } index++; } diff --git a/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs b/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs index 8665b7ca..fd10537a 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs @@ -54,7 +54,9 @@ namespace Newtonsoft.Json.Linq public int GetHashCode(JToken obj) { if (obj == null) + { return 0; + } return obj.GetDeepHashCode(); } diff --git a/Src/Newtonsoft.Json/Linq/JTokenReader.cs b/Src/Newtonsoft.Json/Linq/JTokenReader.cs index c8c3dd25..e288e74b 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenReader.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenReader.cs @@ -126,13 +126,19 @@ namespace Newtonsoft.Json.Linq if (CurrentState != State.Start) { if (_current == null) + { return false; + } JContainer container = _current as JContainer; if (container != null && _parent != container) + { return ReadInto(container); + } else + { return ReadOver(_current); + } } _current = _root; @@ -156,13 +162,17 @@ namespace Newtonsoft.Json.Linq private bool ReadOver(JToken t) { if (t == _root) + { return ReadToEnd(); + } JToken next = t.Next; if ((next == null || next == t) || t == t.Parent.Last) { if (t.Parent == null) + { return ReadToEnd(); + } return SetEnd(t.Parent); } @@ -298,7 +308,9 @@ namespace Newtonsoft.Json.Linq bool IJsonLineInfo.HasLineInfo() { if (CurrentState == State.Start) + { return false; + } IJsonLineInfo info = _current; return (info != null && info.HasLineInfo()); @@ -309,11 +321,15 @@ namespace Newtonsoft.Json.Linq get { if (CurrentState == State.Start) + { return 0; + } IJsonLineInfo info = _current; if (info != null) + { return info.LineNumber; + } return 0; } @@ -324,11 +340,15 @@ namespace Newtonsoft.Json.Linq get { if (CurrentState == State.Start) + { return 0; + } IJsonLineInfo info = _current; if (info != null) + { return info.LinePosition; + } return 0; } @@ -346,16 +366,22 @@ namespace Newtonsoft.Json.Linq if (!string.IsNullOrEmpty(_initialPath)) { if (string.IsNullOrEmpty(path)) + { return _initialPath; + } if (path.StartsWith('[')) + { path = _initialPath + path; + } else + { path = _initialPath + "." + path; + } } return path; } } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index 4db0d6ae..1bed4e4e 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -60,7 +60,9 @@ namespace Newtonsoft.Json.Linq get { if (_token != null) + { return _token; + } return _value; } @@ -113,9 +115,13 @@ namespace Newtonsoft.Json.Linq private void AddParent(JContainer container) { if (_parent == null) + { _token = container; + } else + { _parent.AddAndSkipParentCheck(container); + } _parent = container; _current = container; @@ -127,7 +133,9 @@ namespace Newtonsoft.Json.Linq _parent = _parent.Parent; if (_parent != null && _parent.Type == JTokenType.Property) + { _parent = _parent.Parent; + } } /// @@ -194,7 +202,9 @@ namespace Newtonsoft.Json.Linq _current = _parent.Last; if (_parent.Type == JTokenType.Property) + { _parent = _parent.Parent; + } } else { diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 24fee13e..c2c6ccb8 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -197,9 +197,13 @@ namespace Newtonsoft.Json.Linq { JValue other = node as JValue; if (other == null) + { return false; + } if (other == this) + { return true; + } return ValuesEquals(this, other); } @@ -221,7 +225,9 @@ namespace Newtonsoft.Json.Linq int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2)); if (result != 0) + { return result; + } // converting a fractional number to a BigInteger will lose the fraction // check for fraction if result is two numbers are equal @@ -243,33 +249,53 @@ namespace Newtonsoft.Json.Linq internal static int Compare(JTokenType valueType, object objA, object objB) { if (objA == null && objB == null) + { return 0; + } if (objA != null && objB == null) + { return 1; + } if (objA == null && objB != null) + { return -1; + } switch (valueType) { case JTokenType.Integer: #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (objA is BigInteger) + { return CompareBigInteger((BigInteger)objA, objB); + } if (objB is BigInteger) + { return -CompareBigInteger((BigInteger)objB, objA); + } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) + { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); + } else if (objA is float || objB is float || objA is double || objB is double) + { return CompareFloat(objA, objB); + } else + { return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)); + } case JTokenType.Float: #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (objA is BigInteger) + { return CompareBigInteger((BigInteger)objA, objB); + } if (objB is BigInteger) + { return -CompareBigInteger((BigInteger)objB, objA); + } #endif return CompareFloat(objA, objB); case JTokenType.Comment: @@ -294,10 +320,14 @@ namespace Newtonsoft.Json.Linq #if !NET20 if (objB is DateTimeOffset) + { date2 = ((DateTimeOffset)objB).DateTime; + } else #endif + { date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture); + } return date1.CompareTo(date2); #if !NET20 @@ -308,28 +338,40 @@ namespace Newtonsoft.Json.Linq DateTimeOffset date2; if (objB is DateTimeOffset) + { date2 = (DateTimeOffset)objB; + } else + { date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)); + } return date1.CompareTo(date2); } #endif case JTokenType.Bytes: if (!(objB is byte[])) + { throw new ArgumentException("Object must be of type byte[]."); + } byte[] bytes1 = objA as byte[]; byte[] bytes2 = objB as byte[]; if (bytes1 == null) + { return -1; + } if (bytes2 == null) + { return 1; + } return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2); case JTokenType.Guid: if (!(objB is Guid)) + { throw new ArgumentException("Object must be of type Guid."); + } Guid guid1 = (Guid)objA; Guid guid2 = (Guid)objB; @@ -337,7 +379,9 @@ namespace Newtonsoft.Json.Linq return guid1.CompareTo(guid2); case JTokenType.Uri: if (!(objB is Uri)) + { throw new ArgumentException("Object must be of type Uri."); + } Uri uri1 = (Uri)objA; Uri uri2 = (Uri)objB; @@ -345,7 +389,9 @@ namespace Newtonsoft.Json.Linq return Comparer.Default.Compare(uri1.ToString(), uri2.ToString()); case JTokenType.TimeSpan: if (!(objB is TimeSpan)) + { throw new ArgumentException("Object must be of type TimeSpan."); + } TimeSpan ts1 = (TimeSpan)objA; TimeSpan ts2 = (TimeSpan)objB; @@ -363,7 +409,9 @@ namespace Newtonsoft.Json.Linq // take into account possible floating point errors if (MathUtils.ApproxEquals(d1, d2)) + { return 0; + } return d1.CompareTo(d2); } @@ -562,40 +610,68 @@ namespace Newtonsoft.Json.Linq private static JTokenType GetValueType(JTokenType? current, object value) { if (value == null) + { return JTokenType.Null; + } #if !(DOTNET || PORTABLE40 || PORTABLE) else if (value == DBNull.Value) + { return JTokenType.Null; + } #endif else if (value is string) + { return GetStringValueType(current); + } else if (value is long || value is int || value is short || value is sbyte || value is ulong || value is uint || value is ushort || value is byte) + { return JTokenType.Integer; + } else if (value is Enum) + { return JTokenType.Integer; + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) else if (value is BigInteger) + { return JTokenType.Integer; + } #endif else if (value is double || value is float || value is decimal) + { return JTokenType.Float; + } else if (value is DateTime) + { return JTokenType.Date; + } #if !NET20 else if (value is DateTimeOffset) + { return JTokenType.Date; + } #endif else if (value is byte[]) + { return JTokenType.Bytes; + } else if (value is bool) + { return JTokenType.Boolean; + } else if (value is Guid) + { return JTokenType.Guid; + } else if (value is Uri) + { return JTokenType.Uri; + } else if (value is TimeSpan) + { return JTokenType.TimeSpan; + } throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } @@ -603,7 +679,9 @@ namespace Newtonsoft.Json.Linq private static JTokenType GetStringValueType(JTokenType? current) { if (current == null) + { return JTokenType.String; + } switch (current.Value) { @@ -638,7 +716,9 @@ namespace Newtonsoft.Json.Linq Type newType = (value != null) ? value.GetType() : null; if (currentType != newType) + { _valueType = GetValueType(_valueType, value); + } _value = value; } @@ -677,27 +757,45 @@ namespace Newtonsoft.Json.Linq return; case JTokenType.Integer: if (_value is int) + { writer.WriteValue((int)_value); + } else if (_value is long) + { writer.WriteValue((long)_value); + } else if (_value is ulong) + { writer.WriteValue((ulong)_value); + } #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) else if (_value is BigInteger) + { writer.WriteValue((BigInteger)_value); + } #endif else + { writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); + } return; case JTokenType.Float: if (_value is decimal) + { writer.WriteValue((decimal)_value); + } else if (_value is double) + { writer.WriteValue((double)_value); + } else if (_value is float) + { writer.WriteValue((float)_value); + } else + { writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); + } return; case JTokenType.String: writer.WriteValue((_value != null) ? _value.ToString() : null); @@ -708,10 +806,14 @@ namespace Newtonsoft.Json.Linq case JTokenType.Date: #if !NET20 if (_value is DateTimeOffset) + { writer.WriteValue((DateTimeOffset)_value); + } else #endif + { writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); + } return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); @@ -721,7 +823,7 @@ namespace Newtonsoft.Json.Linq writer.WriteValue((_value != null) ? _value.ToString() : null); return; case JTokenType.Uri: - writer.WriteValue((_value != null) ? ((Uri) _value).OriginalString : null); + writer.WriteValue((_value != null) ? ((Uri)_value).OriginalString : null); return; } @@ -751,7 +853,9 @@ namespace Newtonsoft.Json.Linq public bool Equals(JValue other) { if (other == null) + { return false; + } return ValuesEquals(this, other); } @@ -769,11 +873,15 @@ namespace Newtonsoft.Json.Linq public override bool Equals(object obj) { if (obj == null) + { return false; + } JValue otherValue = obj as JValue; if (otherValue != null) + { return Equals(otherValue); + } return base.Equals(obj); } @@ -787,7 +895,9 @@ namespace Newtonsoft.Json.Linq public override int GetHashCode() { if (_value == null) + { return 0; + } return _value.GetHashCode(); } @@ -801,7 +911,9 @@ namespace Newtonsoft.Json.Linq public override string ToString() { if (_value == null) + { return string.Empty; + } return _value.ToString(); } @@ -841,13 +953,19 @@ namespace Newtonsoft.Json.Linq public string ToString(string format, IFormatProvider formatProvider) { if (_value == null) + { return string.Empty; + } IFormattable formattable = _value as IFormattable; if (formattable != null) + { return formattable.ToString(format, formatProvider); + } else + { return _value.ToString(); + } } #if !(NET35 || NET20 || PORTABLE40) @@ -934,7 +1052,9 @@ namespace Newtonsoft.Json.Linq int IComparable.CompareTo(object obj) { if (obj == null) + { return 1; + } object otherValue = (obj is JValue) ? ((JValue)obj).Value : obj; @@ -962,7 +1082,9 @@ namespace Newtonsoft.Json.Linq public int CompareTo(JValue obj) { if (obj == null) + { return 1; + } return Compare(_valueType, _value, obj._value); } @@ -971,12 +1093,16 @@ namespace Newtonsoft.Json.Linq TypeCode IConvertible.GetTypeCode() { if (_value == null) + { return TypeCode.Empty; + } IConvertible convertable = _value as IConvertible; - + if (convertable == null) + { return TypeCode.Object; + } return convertable.GetTypeCode(); } @@ -1056,5 +1182,5 @@ namespace Newtonsoft.Json.Linq return ToObject(conversionType); } #endif - } + } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JsonMergeSettings.cs b/Src/Newtonsoft.Json/Linq/JsonMergeSettings.cs index 3f33c6a3..5acfb173 100644 --- a/Src/Newtonsoft.Json/Linq/JsonMergeSettings.cs +++ b/Src/Newtonsoft.Json/Linq/JsonMergeSettings.cs @@ -19,8 +19,10 @@ namespace Newtonsoft.Json.Linq set { if (value < MergeArrayHandling.Concat || value > MergeArrayHandling.Merge) + { throw new ArgumentOutOfRangeException("value"); - + } + _mergeArrayHandling = value; } } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs index 6206edce..40240745 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs @@ -17,7 +17,9 @@ namespace Newtonsoft.Json.Linq.JsonPath JToken v = GetTokenIndex(t, errorWhenNoMatch, Index.Value); if (v != null) + { yield return v; + } } else { @@ -31,7 +33,9 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (errorWhenNoMatch) + { throw new JsonException("Index * not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); + } } } } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs index fe01f14f..81d64e36 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/ArrayMultipleIndexFilter.cs @@ -15,7 +15,9 @@ namespace Newtonsoft.Json.Linq.JsonPath JToken v = GetTokenIndex(t, errorWhenNoMatch, i); if (v != null) + { yield return v; + } } } } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs index ee229dec..97933e8f 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs @@ -14,7 +14,9 @@ namespace Newtonsoft.Json.Linq.JsonPath public override IEnumerable ExecuteFilter(IEnumerable current, bool errorWhenNoMatch) { if (Step == 0) + { throw new JsonException("Step cannot be zero."); + } foreach (JToken t in current) { @@ -27,10 +29,16 @@ namespace Newtonsoft.Json.Linq.JsonPath int stopIndex = End ?? ((stepCount > 0) ? a.Count : -1); // start from the end of the list if start is negitive - if (Start < 0) startIndex = a.Count + startIndex; + if (Start < 0) + { + startIndex = a.Count + startIndex; + } // end from the start of the list if stop is negitive - if (End < 0) stopIndex = a.Count + stopIndex; + if (End < 0) + { + stopIndex = a.Count + stopIndex; + } // ensure indexes keep within collection bounds startIndex = Math.Max(startIndex, (stepCount > 0) ? 0 : int.MinValue); @@ -50,15 +58,19 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (errorWhenNoMatch) + { throw new JsonException("Array slice of {0} to {1} returned no results.".FormatWith(CultureInfo.InvariantCulture, Start != null ? Start.Value.ToString(CultureInfo.InvariantCulture) : "*", End != null ? End.Value.ToString(CultureInfo.InvariantCulture) : "*")); + } } } else { if (errorWhenNoMatch) + { throw new JsonException("Array slice is not valid on {0}.".FormatWith(CultureInfo.InvariantCulture, t.GetType().Name)); + } } } } @@ -66,7 +78,9 @@ namespace Newtonsoft.Json.Linq.JsonPath private bool IsValid(int index, int stopIndex, bool positiveStep) { if (positiveStep) + { return (index < stopIndex); + } return (index > stopIndex); } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs index d3fe1f01..e349466b 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/FieldFilter.cs @@ -20,9 +20,13 @@ namespace Newtonsoft.Json.Linq.JsonPath JToken v = o[Name]; if (v != null) + { yield return v; + } else if (errorWhenNoMatch) + { throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, Name)); + } } else { @@ -35,7 +39,9 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (errorWhenNoMatch) + { throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, Name ?? "*", t.GetType().Name)); + } } } } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs index 8349f4ae..940818a3 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs @@ -25,16 +25,22 @@ namespace Newtonsoft.Json.Linq.JsonPath JToken v = o[name]; if (v != null) + { yield return v; + } if (errorWhenNoMatch) + { throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, name)); + } } } else { if (errorWhenNoMatch) + { throw new JsonException("Properties {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", Names.Select(n => "'" + n + "'").ToArray()), t.GetType().Name)); + } } } } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/JPath.cs b/Src/Newtonsoft.Json/Linq/JsonPath/JPath.cs index 0941f3e4..49d80f1a 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/JPath.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/JPath.cs @@ -54,12 +54,16 @@ namespace Newtonsoft.Json.Linq.JsonPath EatWhitespace(); if (_expression.Length == _currentIndex) + { return; + } if (_expression[_currentIndex] == '$') { if (_expression.Length == 1) + { return; + } // only increment position for "$." or "$[" // otherwise assume property that starts with $ @@ -78,7 +82,9 @@ namespace Newtonsoft.Json.Linq.JsonPath EatWhitespace(); if (_currentIndex < _expression.Length) + { throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]); + } } } @@ -118,14 +124,18 @@ namespace Newtonsoft.Json.Linq.JsonPath case ' ': //EatWhitespace(); if (_currentIndex < _expression.Length) + { ended = true; + } break; case '.': if (_currentIndex > currentPartStartIndex) { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") + { member = null; + } PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); scan = false; @@ -148,7 +158,9 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (followingIndexer) + { throw new JsonException("Unexpected character following indexer: " + currentChar); + } _currentIndex++; } @@ -162,7 +174,9 @@ namespace Newtonsoft.Json.Linq.JsonPath { string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); if (member == "*") + { member = null; + } PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member }; filters.Add(filter); } @@ -170,7 +184,9 @@ namespace Newtonsoft.Json.Linq.JsonPath { // no field name following dot in path and at end of base path/query if (followingDot && (atPathEnd || query)) + { throw new JsonException("Unexpected end while parsing path."); + } } return atPathEnd; @@ -228,7 +244,9 @@ namespace Newtonsoft.Json.Linq.JsonPath if (indexes != null) { if (length == 0) + { throw new JsonException("Array index expected."); + } string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); @@ -244,9 +262,13 @@ namespace Newtonsoft.Json.Linq.JsonPath int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 1) + { endIndex = index; + } else + { step = index; + } } return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step }; @@ -254,22 +276,29 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (length == 0) + { throw new JsonException("Array index expected."); + } string indexer = _expression.Substring(start, length); int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); return new ArrayIndexFilter { Index = index }; } - } else if (currentCharacter == ',') + } + else if (currentCharacter == ',') { int length = (end ?? _currentIndex) - start; if (length == 0) + { throw new JsonException("Array index expected."); + } if (indexes == null) + { indexes = new List(); + } string indexer = _expression.Substring(start, length); indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); @@ -288,7 +317,9 @@ namespace Newtonsoft.Json.Linq.JsonPath EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) + { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); + } return new ArrayIndexFilter(); } @@ -302,11 +333,17 @@ namespace Newtonsoft.Json.Linq.JsonPath int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); if (colonCount == 0) + { startIndex = index; + } else if (colonCount == 1) + { endIndex = index; + } else + { step = index; + } } colonCount++; @@ -325,11 +362,12 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (end != null) + { throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); + } _currentIndex++; } - } throw new JsonException("Path ended with open indexer."); @@ -340,7 +378,9 @@ namespace Newtonsoft.Json.Linq.JsonPath while (_currentIndex < _expression.Length) { if (_expression[_currentIndex] != ' ') + { break; + } _currentIndex++; } @@ -352,7 +392,9 @@ namespace Newtonsoft.Json.Linq.JsonPath EnsureLength("Path ended with open indexer."); if (_expression[_currentIndex] != '(') + { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); + } _currentIndex++; @@ -363,7 +405,9 @@ namespace Newtonsoft.Json.Linq.JsonPath EatWhitespace(); if (_expression[_currentIndex] != indexerCloseChar) + { throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]); + } return new QueryFilter { @@ -381,14 +425,18 @@ namespace Newtonsoft.Json.Linq.JsonPath EatWhitespace(); if (_expression[_currentIndex] != '@') + { throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]); + } _currentIndex++; List expressionPath = new List(); if (ParsePath(expressionPath, _currentIndex, true)) + { throw new JsonException("Path ended with open query."); + } EatWhitespace(); EnsureLength("Path ended with open query."); @@ -428,7 +476,7 @@ namespace Newtonsoft.Json.Linq.JsonPath parentExpression.Expressions.Add(booleanExpression); return rootExpression; } - + return booleanExpression; } if (_expression[_currentIndex] == '&' && Match("&&")) @@ -438,12 +486,16 @@ namespace Newtonsoft.Json.Linq.JsonPath CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; if (parentExpression != null) + { parentExpression.Expressions.Add(andExpression); + } parentExpression = andExpression; if (rootExpression == null) + { rootExpression = parentExpression; + } } parentExpression.Expressions.Add(booleanExpression); @@ -455,12 +507,16 @@ namespace Newtonsoft.Json.Linq.JsonPath CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; if (parentExpression != null) + { parentExpression.Expressions.Add(orExpression); + } parentExpression = orExpression; if (rootExpression == null) + { rootExpression = parentExpression; + } } parentExpression.Expressions.Add(booleanExpression); @@ -494,17 +550,25 @@ namespace Newtonsoft.Json.Linq.JsonPath { double d; if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d)) + { return d; + } else + { throw new JsonException("Could not read query value."); + } } else { long l; if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l)) + { return l; + } else + { throw new JsonException("Could not read query value."); + } } } else @@ -517,17 +581,23 @@ namespace Newtonsoft.Json.Linq.JsonPath else if (currentChar == 't') { if (Match("true")) + { return true; + } } else if (currentChar == 'f') { if (Match("false")) + { return false; + } } else if (currentChar == 'n') { if (Match("null")) + { return null; + } } throw new JsonException("Could not read query value."); @@ -546,11 +616,17 @@ namespace Newtonsoft.Json.Linq.JsonPath _currentIndex++; if (_expression[_currentIndex] == '\'') + { sb.Append('\''); + } else if (_expression[_currentIndex] == '\\') + { sb.Append('\\'); + } else + { throw new JsonException(@"Unknown escape chracter: \" + _expression[_currentIndex]); + } _currentIndex++; } @@ -577,9 +653,13 @@ namespace Newtonsoft.Json.Linq.JsonPath foreach (char c in s) { if (currentPosition < _expression.Length && _expression[currentPosition] == c) + { currentPosition++; + } else + { return false; + } } _currentIndex = currentPosition; @@ -589,20 +669,34 @@ namespace Newtonsoft.Json.Linq.JsonPath private QueryOperator ParseOperator() { if (_currentIndex + 1 >= _expression.Length) + { throw new JsonException("Path ended with open query."); + } if (Match("==")) + { return QueryOperator.Equals; + } if (Match("!=") || Match("<>")) + { return QueryOperator.NotEquals; + } if (Match("<=")) + { return QueryOperator.LessThanOrEquals; + } if (Match("<")) + { return QueryOperator.LessThan; + } if (Match(">=")) + { return QueryOperator.GreaterThanOrEquals; + } if (Match(">")) + { return QueryOperator.GreaterThan; + } throw new JsonException("Could not read query operator."); } @@ -636,7 +730,9 @@ namespace Newtonsoft.Json.Linq.JsonPath EatWhitespace(); if (fields == null) + { fields = new List(); + } fields.Add(field); } @@ -652,7 +748,9 @@ namespace Newtonsoft.Json.Linq.JsonPath private void EnsureLength(string message) { if (_currentIndex >= _expression.Length) + { throw new JsonException(message); + } } internal IEnumerable Evaluate(JToken t, bool errorWhenNoMatch) diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs index 90cc5bb0..c1bce170 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs @@ -18,7 +18,9 @@ namespace Newtonsoft.Json.Linq.JsonPath if (a.Count <= index) { if (errorWhenNoMatch) + { throw new JsonException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); + } return null; } @@ -30,7 +32,9 @@ namespace Newtonsoft.Json.Linq.JsonPath if (c.Count <= index) { if (errorWhenNoMatch) + { throw new JsonException("Index {0} outside the bounds of JConstructor.".FormatWith(CultureInfo.InvariantCulture, index)); + } return null; } @@ -40,7 +44,9 @@ namespace Newtonsoft.Json.Linq.JsonPath else { if (errorWhenNoMatch) + { throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, t.GetType().Name)); + } return null; } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs b/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs index 9e4c9e3c..3b5c44e4 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs @@ -44,14 +44,18 @@ namespace Newtonsoft.Json.Linq.JsonPath foreach (QueryExpression e in Expressions) { if (!e.IsMatch(t)) + { return false; + } } return true; case QueryOperator.Or: foreach (QueryExpression e in Expressions) { if (e.IsMatch(t)) + { return true; + } } return false; default: @@ -76,27 +80,39 @@ namespace Newtonsoft.Json.Linq.JsonPath { case QueryOperator.Equals: if (v != null && EqualsWithStringCoercion(v, Value)) + { return true; + } break; case QueryOperator.NotEquals: if (v != null && !EqualsWithStringCoercion(v, Value)) + { return true; + } break; case QueryOperator.GreaterThan: if (v != null && v.CompareTo(Value) > 0) + { return true; + } break; case QueryOperator.GreaterThanOrEquals: if (v != null && v.CompareTo(Value) >= 0) + { return true; + } break; case QueryOperator.LessThan: if (v != null && v.CompareTo(Value) < 0) + { return true; + } break; case QueryOperator.LessThanOrEquals: if (v != null && v.CompareTo(Value) <= 0) + { return true; + } break; case QueryOperator.Exists: return true; diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs index bbdfbcbf..9dab576f 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs @@ -14,7 +14,9 @@ namespace Newtonsoft.Json.Linq.JsonPath foreach (JToken v in t) { if (Expression.IsMatch(v)) + { yield return v; + } } } } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs b/Src/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs index f07992fb..930adc49 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs @@ -11,7 +11,9 @@ namespace Newtonsoft.Json.Linq.JsonPath foreach (JToken root in current) { if (Name == null) + { yield return root; + } JToken value = root; JToken container = root; @@ -30,7 +32,9 @@ namespace Newtonsoft.Json.Linq.JsonPath } if (value == null || value == root) + { break; + } value = value.Next; } @@ -39,12 +43,16 @@ namespace Newtonsoft.Json.Linq.JsonPath if (e != null) { if (e.Name == Name) + { yield return e.Value; + } } else { if (Name == null) + { yield return value; + } } container = value as JContainer; diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.project.json b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.project.json index 201ace56..4f8b3cdc 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.project.json +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.project.json @@ -3,6 +3,6 @@ "net20": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.project.json b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.project.json index f6c8ba31..f017abb4 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.project.json +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.project.json @@ -3,6 +3,6 @@ "net35": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net40.project.json b/Src/Newtonsoft.Json/Newtonsoft.Json.Net40.project.json index 7e89b85a..1a6c3a90 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net40.project.json +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net40.project.json @@ -3,6 +3,6 @@ "net40": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.project.json b/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.project.json index 5541d981..65093cbf 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.project.json +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.project.json @@ -3,6 +3,6 @@ ".NETPortable,Version=v4.5,Profile=Profile259": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Portable40.project.json b/Src/Newtonsoft.Json/Newtonsoft.Json.Portable40.project.json index 45a596f3..c78108a4 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Portable40.project.json +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Portable40.project.json @@ -3,6 +3,6 @@ ".NETPortable,Version=v4.0,Profile=Profile328": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.project.json b/Src/Newtonsoft.Json/Newtonsoft.Json.project.json index 8a7fd6ef..572bc9ed 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.project.json +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.project.json @@ -3,6 +3,6 @@ "net45": {} }, "runtimes": { - "win-anycpu": {} + "win": {} } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index 27343e4e..bfc61ab8 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -48,11 +48,13 @@ using System.Security; [assembly: AssemblyTitle("Json.NET .NET 4.0")] [assembly: AllowPartiallyTrustedCallers] #else + [assembly: AssemblyTitle("Json.NET")] [assembly: AllowPartiallyTrustedCallers] #endif #if !SIGNED + [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")] #else @@ -93,4 +95,4 @@ using System.Security; [assembly: AssemblyVersion("7.0.0.0")] [assembly: AssemblyFileVersion("7.0.2.18802")] -[assembly: CLSCompliant(true)] +[assembly: CLSCompliant(true)] \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Schema/Extensions.cs b/Src/Newtonsoft.Json/Schema/Extensions.cs index b8b7cc9b..b1876e60 100644 --- a/Src/Newtonsoft.Json/Schema/Extensions.cs +++ b/Src/Newtonsoft.Json/Schema/Extensions.cs @@ -124,7 +124,9 @@ namespace Newtonsoft.Json.Schema { reader.Schema = schema; if (validationEventHandler != null) + { reader.ValidationEventHandler += validationEventHandler; + } while (reader.Read()) { diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index b9be9f1f..69475201 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -101,7 +101,9 @@ namespace Newtonsoft.Json.Schema bool locationReference = (reference.StartsWith("#", StringComparison.Ordinal)); if (locationReference) + { reference = UnescapeReference(reference); + } JsonSchema resolvedSchema = _resolver.GetSchema(reference); @@ -123,28 +125,40 @@ namespace Newtonsoft.Json.Schema { int index; if (int.TryParse(part, out index) && index >= 0 && index < currentToken.Count()) + { currentToken = currentToken[index]; + } else + { currentToken = null; + } } if (currentToken == null) + { break; + } } if (currentToken != null) + { resolvedSchema = BuildSchema(currentToken); + } } if (resolvedSchema == null) + { throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference)); + } } schema = resolvedSchema; } if (schema.ReferencesResolved) + { return schema; + } schema.ReferencesResolved = true; @@ -165,7 +179,9 @@ namespace Newtonsoft.Json.Schema } if (schema.AdditionalItems != null) + { schema.AdditionalItems = ResolveReferences(schema.AdditionalItems); + } if (schema.PatternProperties != null) { @@ -184,7 +200,9 @@ namespace Newtonsoft.Json.Schema } if (schema.AdditionalProperties != null) + { schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties); + } return schema; } @@ -193,7 +211,9 @@ namespace Newtonsoft.Json.Schema { JObject schemaObject = token as JObject; if (schemaObject == null) + { throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } JToken referenceToken; if (schemaObject.TryGetValue(JsonTypeReflector.RefPropertyName, out referenceToken)) @@ -206,12 +226,16 @@ namespace Newtonsoft.Json.Schema string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty); if (!string.IsNullOrEmpty(location)) + { location = "/" + location; + } location = "#" + location; JsonSchema existingSchema; if (_documentSchemas.TryGetValue(location, out existingSchema)) + { return existingSchema; + } Push(new JsonSchema { Location = location }); @@ -332,17 +356,23 @@ namespace Newtonsoft.Json.Schema { JsonSchema schema = BuildSchema(token); if (schema != null) + { schemas.Add(schema); + } } if (schemas.Count > 0) + { CurrentSchema.Extends = schemas; + } } private void ProcessEnum(JToken token) { if (token.Type != JTokenType.Array) + { throw JsonException.Create(token, token.Path, "Expected Array token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } CurrentSchema.Enum = new List(); @@ -355,17 +385,25 @@ namespace Newtonsoft.Json.Schema private void ProcessAdditionalProperties(JToken token) { if (token.Type == JTokenType.Boolean) + { CurrentSchema.AllowAdditionalProperties = (bool)token; + } else + { CurrentSchema.AdditionalProperties = BuildSchema(token); + } } private void ProcessAdditionalItems(JToken token) { if (token.Type == JTokenType.Boolean) + { CurrentSchema.AllowAdditionalItems = (bool)token; + } else + { CurrentSchema.AdditionalItems = BuildSchema(token); + } } private IDictionary ProcessProperties(JToken token) @@ -373,12 +411,16 @@ namespace Newtonsoft.Json.Schema IDictionary properties = new Dictionary(); if (token.Type != JTokenType.Object) + { throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } foreach (JProperty propertyToken in token) { if (properties.ContainsKey(propertyToken.Name)) + { throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name)); + } properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value)); } @@ -419,7 +461,9 @@ namespace Newtonsoft.Json.Schema foreach (JToken typeToken in token) { if (typeToken.Type != JTokenType.String) + { throw JsonException.Create(typeToken, typeToken.Path, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type)); + } type = type | MapType((string)typeToken); } @@ -436,7 +480,9 @@ namespace Newtonsoft.Json.Schema { JsonSchemaType mappedType; if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType)) + { throw new JsonException("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); + } return mappedType; } @@ -446,4 +492,4 @@ namespace Newtonsoft.Json.Schema return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key; } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs index 9b44cee3..f9503dbd 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs @@ -48,7 +48,6 @@ namespace Newtonsoft.Json.Schema /// The line number indicating where the error occurred. public int LineNumber { get; private set; } - /// /// Gets the line position indicating where the error occurred. /// diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index a61f9ec6..0ecde46a 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -66,7 +66,9 @@ namespace Newtonsoft.Json.Schema get { if (_contractResolver == null) + { return DefaultContractResolver.Instance; + } return _contractResolver; } @@ -175,7 +177,9 @@ namespace Newtonsoft.Json.Schema JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title)) + { return containerAttribute.Title; + } return null; } @@ -185,12 +189,16 @@ namespace Newtonsoft.Json.Schema JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) + { return containerAttribute.Description; + } #if !(DOTNET || PORTABLE40 || PORTABLE) DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute(type); if (descriptionAttribute != null) + { return descriptionAttribute.Description; + } #endif return null; @@ -201,10 +209,14 @@ namespace Newtonsoft.Json.Schema JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id)) + { return containerAttribute.Id; + } if (explicitOnly) + { return null; + } switch (UndefinedSchemaIdHandling) { @@ -232,9 +244,13 @@ namespace Newtonsoft.Json.Schema // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) + { resolvedSchema.Type |= JsonSchemaType.Null; + } if (required && resolvedSchema.Required != true) + { resolvedSchema.Required = true; + } return resolvedSchema; } @@ -252,16 +268,22 @@ namespace Newtonsoft.Json.Schema { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) + { return converterSchema; + } } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) + { CurrentSchema.Id = explicitId; + } if (required) + { CurrentSchema.Required = true; + } CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); @@ -359,7 +381,9 @@ namespace Newtonsoft.Json.Schema private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) + { return type | JsonSchemaType.Null; + } return type; } @@ -384,14 +408,18 @@ namespace Newtonsoft.Json.Schema JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional); if (property.DefaultValue != null) + { propertySchema.Default = JToken.FromObject(property.DefaultValue); + } CurrentSchema.Properties.Add(property.PropertyName, propertySchema); } } if (type.IsSealed()) + { CurrentSchema.AllowAdditionalProperties = false; + } } #if !(DOTNET || PORTABLE || PORTABLE40) @@ -405,15 +433,21 @@ namespace Newtonsoft.Json.Schema { // default value is Any if (value == null) + { return true; + } bool match = ((value & flag) == flag); if (match) + { return true; + } // integer is a subset of float if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float) + { return true; + } return false; } @@ -425,7 +459,9 @@ namespace Newtonsoft.Json.Schema { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) + { type = Nullable.GetUnderlyingType(type); + } } PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type); @@ -459,7 +495,7 @@ namespace Newtonsoft.Json.Schema case PrimitiveTypeCode.Double: case PrimitiveTypeCode.Decimal: return schemaType | JsonSchemaType.Float; - // convert to string? + // convert to string? case PrimitiveTypeCode.DateTime: #if !NET20 case PrimitiveTypeCode.DateTimeOffset: diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaModel.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaModel.cs index b5ffcd45..7ff97062 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaModel.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaModel.cs @@ -103,7 +103,9 @@ namespace Newtonsoft.Json.Schema if (schema.Enum != null) { if (model.Enum == null) + { model.Enum = new List(); + } model.Enum.AddRangeDistinct(schema.Enum, JToken.EqualityComparer); } @@ -112,7 +114,9 @@ namespace Newtonsoft.Json.Schema if (schema.Pattern != null) { if (model.Patterns == null) + { model.Patterns = new List(); + } model.Patterns.AddDistinct(schema.Pattern); } diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs index 2e910ede..84b8c85d 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs @@ -58,7 +58,9 @@ namespace Newtonsoft.Json.Schema if (existingNode != null) { if (existingNode.Schemas.Contains(schema)) + { return existingNode; + } newId = JsonSchemaNode.GetId(existingNode.Schemas.Union(new[] { schema })); } @@ -68,7 +70,9 @@ namespace Newtonsoft.Json.Schema } if (_nodes.Contains(newId)) + { return _nodes[newId]; + } JsonSchemaNode currentNode = (existingNode != null) ? existingNode.Combine(schema) @@ -89,10 +93,14 @@ namespace Newtonsoft.Json.Schema } if (schema.AdditionalItems != null) + { AddAdditionalItems(currentNode, schema.AdditionalItems); + } if (schema.AdditionalProperties != null) + { AddAdditionalProperties(currentNode, schema.AdditionalProperties); + } if (schema.Extends != null) { @@ -156,7 +164,9 @@ namespace Newtonsoft.Json.Schema { JsonSchemaModel model; if (_nodeModels.TryGetValue(node, out model)) + { return model; + } model = JsonSchemaModel.Create(node.Schemas); _nodeModels[node] = model; @@ -164,28 +174,38 @@ namespace Newtonsoft.Json.Schema foreach (KeyValuePair property in node.Properties) { if (model.Properties == null) + { model.Properties = new Dictionary(); + } model.Properties[property.Key] = BuildNodeModel(property.Value); } foreach (KeyValuePair property in node.PatternProperties) { if (model.PatternProperties == null) + { model.PatternProperties = new Dictionary(); + } model.PatternProperties[property.Key] = BuildNodeModel(property.Value); } foreach (JsonSchemaNode t in node.Items) { if (model.Items == null) + { model.Items = new List(); + } model.Items.Add(BuildNodeModel(t)); } if (node.AdditionalProperties != null) + { model.AdditionalProperties = BuildNodeModel(node.AdditionalProperties); + } if (node.AdditionalItems != null) + { model.AdditionalItems = BuildNodeModel(node.AdditionalItems); + } return model; } diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaResolver.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaResolver.cs index 79c9db2b..5a8e6ce4 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaResolver.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaResolver.cs @@ -69,7 +69,9 @@ namespace Newtonsoft.Json.Schema JsonSchema schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Id, reference, StringComparison.Ordinal)); if (schema == null) + { schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Location, reference, StringComparison.Ordinal)); + } return schema; } diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs index 6ced56cc..595f877e 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs @@ -70,7 +70,9 @@ namespace Newtonsoft.Json.Schema ValidationUtils.ArgumentNotNull(schema, "schema"); if (!_resolver.LoadedSchemas.Contains(schema)) + { _resolver.LoadedSchemas.Add(schema); + } _writer.WriteStartObject(); WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id); @@ -81,7 +83,9 @@ namespace Newtonsoft.Json.Schema WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden); WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient); if (schema.Type != null) + { WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value); + } if (!schema.AllowAdditionalProperties) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); @@ -138,7 +142,9 @@ namespace Newtonsoft.Json.Schema schema.Default.WriteTo(_writer); } if (schema.Disallow != null) + { WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value); + } if (schema.Extends != null && schema.Extends.Count > 0) { _writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName); @@ -177,7 +183,9 @@ namespace Newtonsoft.Json.Schema private void WriteItems(JsonSchema schema) { if (schema.Items == null && !schema.PositionalItemsValidation) + { return; + } _writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName); @@ -210,12 +218,18 @@ namespace Newtonsoft.Json.Schema { IList types; if (System.Enum.IsDefined(typeof(JsonSchemaType), type)) + { types = new List { type }; + } else + { types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList(); + } if (types.Count == 0) + { return; + } writer.WritePropertyName(propertyName); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 30a73960..58e046e1 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -73,7 +73,9 @@ namespace Newtonsoft.Json.Serialization public override bool Equals(object obj) { if (!(obj is ResolverContractKey)) + { return false; + } return Equals((ResolverContractKey)obj); } @@ -151,7 +153,7 @@ namespace Newtonsoft.Json.Serialization /// Gets or sets the default members search flags. /// /// The default members search flags. - [ObsoleteAttribute("DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")] + [ObsoleteAttribute("DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.")] public BindingFlags DefaultMembersSearchFlags { get; set; } #else private BindingFlags DefaultMembersSearchFlags; @@ -216,9 +218,13 @@ namespace Newtonsoft.Json.Serialization internal DefaultContractResolverState GetState() { if (_sharedCache) + { return _sharedState; + } else + { return _instanceState; + } } /// @@ -229,7 +235,9 @@ namespace Newtonsoft.Json.Serialization public virtual JsonContract ResolveContract(Type type) { if (type == null) + { throw new ArgumentNullException("type"); + } DefaultContractResolverState state = GetState(); @@ -303,15 +311,23 @@ namespace Newtonsoft.Json.Serialization // add members that are explicitly marked with JsonProperty/DataMember attribute // or are a field if serializing just fields if (JsonTypeReflector.GetAttribute(member) != null) + { serializableMembers.Add(member); + } else if (JsonTypeReflector.GetAttribute(member) != null) + { serializableMembers.Add(member); + } #if !NET20 else if (dataContractAttribute != null && JsonTypeReflector.GetAttribute(member) != null) + { serializableMembers.Add(member); + } #endif else if (memberSerialization == MemberSerialization.Fields && member.MemberType() == MemberTypes.Field) + { serializableMembers.Add(member); + } } } } @@ -320,7 +336,9 @@ namespace Newtonsoft.Json.Serialization Type match; // don't include EntityKey on entities objects... this is a bit hacky if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out match)) + { serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList(); + } #endif } else @@ -330,7 +348,9 @@ namespace Newtonsoft.Json.Serialization { FieldInfo field = member as FieldInfo; if (field != null && !field.IsStatic) + { serializableMembers.Add(member); + } } } @@ -344,7 +364,9 @@ namespace Newtonsoft.Json.Serialization if (propertyInfo != null) { if (propertyInfo.PropertyType.IsGenericType() && propertyInfo.PropertyType.GetGenericTypeDefinition().FullName == "System.Data.Objects.DataClasses.EntityReference`1") + { return false; + } } return true; @@ -373,7 +395,9 @@ namespace Newtonsoft.Json.Serialization JsonObjectAttribute attribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); if (attribute != null) + { contract.ItemRequired = attribute._itemRequired; + } if (contract.IsInstantiable) { @@ -393,7 +417,9 @@ namespace Newtonsoft.Json.Serialization // mimic DataContractSerializer behaviour when populating fields by overriding default creator to create an uninitialized object // note that this is only possible when the application is fully trusted so fall back to using the default constructor (if available) in partial trust if (JsonTypeReflector.FullyTrusted) + { contract.DefaultCreator = contract.GetUninitializedObject; + } #endif } else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic) @@ -411,7 +437,9 @@ namespace Newtonsoft.Json.Serialization MemberInfo extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType); if (extensionDataMember != null) + { SetExtensionDataDelegates(contract, extensionDataMember); + } return contract; } @@ -431,14 +459,20 @@ namespace Newtonsoft.Json.Serialization { MemberTypes memberType = m.MemberType(); if (memberType != MemberTypes.Property && memberType != MemberTypes.Field) + { return false; + } // last instance of attribute wins on type if there are multiple if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false)) + { return false; + } if (!ReflectionUtils.CanReadMemberValue(m, true)) + { throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + } Type t = ReflectionUtils.GetMemberUnderlyingType(m); @@ -449,7 +483,9 @@ namespace Newtonsoft.Json.Serialization Type valueType = dictionaryType.GetGenericArguments()[1]; if (keyType.IsAssignableFrom(typeof(string)) && valueType.IsAssignableFrom(typeof(JToken))) + { return true; + } } throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); @@ -462,7 +498,9 @@ namespace Newtonsoft.Json.Serialization { JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute(member); if (extensionDataAttribute == null) + { return; + } Type t = ReflectionUtils.GetMemberUnderlyingType(member); @@ -477,9 +515,13 @@ namespace Newtonsoft.Json.Serialization // change type to a class if it is the base interface so it can be instantiated if needed if (ReflectionUtils.IsGenericDefinition(t, typeof(IDictionary<,>))) + { createdType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); + } else + { createdType = t; + } Func getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(member); Action setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false)) @@ -495,7 +537,9 @@ namespace Newtonsoft.Json.Serialization if (dictionary == null) { if (setExtensionDataDictionary == null) + { throw new JsonSerializationException("Cannot set value onto extension data member '{0}'. The extension data collection is null and it cannot be set.".FormatWith(CultureInfo.InvariantCulture, member.Name)); + } dictionary = createExtensionDataDictionary(); setExtensionDataDictionary(o, dictionary); @@ -504,7 +548,9 @@ namespace Newtonsoft.Json.Serialization // convert object value to JToken so it is compatible with dictionary // could happen because of primitive types, type name handling and references if (isJTokenValueType && !(value is JToken)) + { value = (value != null) ? JToken.FromObject(value) : JValue.CreateNull(); + } setExtensionDataDictionaryValue(dictionary, key, value); }; @@ -517,16 +563,22 @@ namespace Newtonsoft.Json.Serialization { object dictionary = getExtensionDataDictionary(o); if (dictionary == null) + { return null; + } return (IEnumerable>)createEnumerableWrapper(dictionary); }; if (extensionDataAttribute.ReadData) + { contract.ExtensionDataSetter = extensionDataSetter; + } if (extensionDataAttribute.WriteData) + { contract.ExtensionDataGetter = extensionDataGetter; + } } internal struct DictionaryEnumerator : IEnumerable>, IEnumerator> @@ -580,13 +632,19 @@ namespace Newtonsoft.Json.Serialization IList markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList(); if (markedConstructors.Count > 1) + { throw new JsonException("Multiple constructors with the JsonConstructorAttribute."); + } else if (markedConstructors.Count == 1) + { return markedConstructors[0]; + } // little hack to get Version objects to deserialize correctly if (objectType == typeof(Version)) + { return objectType.GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(int) }); + } return null; } @@ -596,9 +654,13 @@ namespace Newtonsoft.Json.Serialization IList constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).ToList(); if (constructors.Count == 1) + { return constructors[0]; + } else + { return null; + } } /// @@ -621,7 +683,9 @@ namespace Newtonsoft.Json.Serialization // type must match as well as name if (matchingMemberProperty != null && matchingMemberProperty.PropertyType != parameterInfo.ParameterType) + { matchingMemberProperty = null; + } // ensure that property will have a name from matching property or from parameterinfo // parameterinfo could have no name if generated by a proxy (I'm looking at you Castle) @@ -665,7 +729,9 @@ namespace Newtonsoft.Json.Serialization property.MemberConverter = property.MemberConverter ?? matchingMemberProperty.MemberConverter; if (!property._hasExplicitDefaultValue && matchingMemberProperty._hasExplicitDefaultValue) + { property.DefaultValue = matchingMemberProperty.DefaultValue; + } property._required = property._required ?? matchingMemberProperty._required; property.IsReference = property.IsReference ?? matchingMemberProperty.IsReference; @@ -697,6 +763,7 @@ namespace Newtonsoft.Json.Serialization #if NET35 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Runtime.Serialization.DataContractAttribute.#get_IsReference()")] #endif + private void InitializeContract(JsonContract contract) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); @@ -710,7 +777,9 @@ namespace Newtonsoft.Json.Serialization DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType); // doesn't have a null value if (dataContractAttribute != null && dataContractAttribute.IsReference) + { contract.IsReference = true; + } } #endif @@ -742,19 +811,29 @@ namespace Newtonsoft.Json.Serialization GetCallbackMethodsForType(t, out onSerializing, out onSerialized, out onDeserializing, out onDeserialized, out onError); if (onSerializing != null) + { contract.OnSerializingCallbacks.AddRange(onSerializing); + } if (onSerialized != null) + { contract.OnSerializedCallbacks.AddRange(onSerialized); + } if (onDeserializing != null) + { contract.OnDeserializingCallbacks.AddRange(onDeserializing); + } if (onDeserialized != null) + { contract.OnDeserializedCallbacks.AddRange(onDeserialized); + } if (onError != null) + { contract.OnErrorCallbacks.AddRange(onError); + } } private void GetCallbackMethodsForType(Type type, out List onSerializing, out List onSerialized, out List onDeserializing, out List onDeserialized, out List onError) @@ -782,7 +861,9 @@ namespace Newtonsoft.Json.Serialization // compact framework errors when getting parameters for a generic method // lame, but generic methods should not be callbacks anyway if (method.ContainsGenericParameters) + { continue; + } Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); @@ -826,11 +907,15 @@ namespace Newtonsoft.Json.Serialization #if !(NET35 || NET20 || PORTABLE || PORTABLE40) // ConcurrentDictionary throws an error in its OnDeserialized so ignore - http://json.codeplex.com/discussions/257093 if (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>)) + { return true; + } #endif #if !(NET35 || NET20) if (t.Name == FSharpUtils.FSharpSetTypeName || t.Name == FSharpUtils.FSharpMapTypeName) + { return true; + } #endif return false; @@ -840,7 +925,9 @@ namespace Newtonsoft.Json.Serialization { #if !(NET35 || NET20) if (t.Name == FSharpUtils.FSharpSetTypeName || t.Name == FSharpUtils.FSharpMapTypeName) + { return true; + } #endif #if DOTNET if (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(ConcurrentDictionary<,>)) @@ -1032,46 +1119,68 @@ namespace Newtonsoft.Json.Serialization protected virtual JsonContract CreateContract(Type objectType) { if (IsJsonPrimitiveType(objectType)) + { return CreatePrimitiveContract(objectType); + } Type t = ReflectionUtils.EnsureNotNullableType(objectType); JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(t); if (containerAttribute is JsonObjectAttribute) + { return CreateObjectContract(objectType); + } if (containerAttribute is JsonArrayAttribute) + { return CreateArrayContract(objectType); + } if (containerAttribute is JsonDictionaryAttribute) + { return CreateDictionaryContract(objectType); + } if (t == typeof(JToken) || t.IsSubclassOf(typeof(JToken))) + { return CreateLinqContract(objectType); + } if (CollectionUtils.IsDictionaryType(t)) + { return CreateDictionaryContract(objectType); + } if (typeof(IEnumerable).IsAssignableFrom(t)) + { return CreateArrayContract(objectType); + } if (CanConvertToString(t)) + { return CreateStringContract(objectType); + } #if !(DOTNET || PORTABLE40 || PORTABLE) if (!IgnoreSerializableInterface && typeof(ISerializable).IsAssignableFrom(t)) + { return CreateISerializableContract(objectType); + } #endif #if !(NET35 || NET20 || PORTABLE40) if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(t)) + { return CreateDynamicContract(objectType); + } #endif #if !PORTABLE // tested last because it is not possible to automatically deserialize custom IConvertible types if (IsIConvertible(t)) + { return CreatePrimitiveContract(t); + } #endif return CreateObjectContract(objectType); @@ -1109,12 +1218,16 @@ namespace Newtonsoft.Json.Serialization && converter.GetType() != typeof(TypeConverter)) { if (converter.CanConvertTo(typeof(string))) + { return true; + } } #endif if (type == typeof(Type) || type.IsSubclassOf(typeof(Type))) + { return true; + } return false; } @@ -1122,29 +1235,43 @@ namespace Newtonsoft.Json.Serialization private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (!method.IsDefined(attributeType, false)) + { return false; + } if (currentCallback != null) + { throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); + } if (prevAttributeType != null) + { throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); + } if (method.IsVirtual) + { throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); + } if (method.ReturnType != typeof(void)) + { throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); + } if (attributeType == typeof(OnErrorAttribute)) { if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext)) + { throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext))); + } } else { if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext)) + { throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext))); + } } prevAttributeType = attributeType; @@ -1155,7 +1282,9 @@ namespace Newtonsoft.Json.Serialization internal static string GetClrTypeFullName(Type type) { if (type.IsGenericTypeDefinition() || !type.ContainsGenericParameters()) + { return type.FullName; + } return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[] { type.Namespace, type.Name }); } @@ -1170,7 +1299,9 @@ namespace Newtonsoft.Json.Serialization { List members = GetSerializableMembers(type); if (members == null) + { throw new JsonSerializationException("Null collection of seralizable members returned."); + } JsonPropertyCollection properties = new JsonPropertyCollection(type); @@ -1208,9 +1339,13 @@ namespace Newtonsoft.Json.Serialization #if !(PORTABLE40 || PORTABLE || DOTNET) if (DynamicCodeGeneration) + { valueProvider = new DynamicValueProvider(member); + } else + { valueProvider = new ReflectionValueProvider(member); + } #elif !(PORTABLE40) valueProvider = new ExpressionValueProvider(member); #else @@ -1264,9 +1399,13 @@ namespace Newtonsoft.Json.Serialization DataMemberAttribute dataMemberAttribute; if (dataContractAttribute != null && memberInfo != null) + { dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo); + } else + { dataMemberAttribute = null; + } #endif JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute(attributeProvider); @@ -1274,13 +1413,19 @@ namespace Newtonsoft.Json.Serialization string mappedName; if (propertyAttribute != null && propertyAttribute.PropertyName != null) + { mappedName = propertyAttribute.PropertyName; + } #if !NET20 else if (dataMemberAttribute != null && dataMemberAttribute.Name != null) + { mappedName = dataMemberAttribute.Name; + } #endif else + { mappedName = name; + } property.PropertyName = ResolvePropertyName(mappedName); property.UnderlyingName = name; @@ -1343,7 +1488,9 @@ namespace Newtonsoft.Json.Serialization DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute(attributeProvider); if (defaultValueAttribute != null) + { property.DefaultValue = defaultValueAttribute.Value; + } property.NullValueHandling = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null; property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null; @@ -1362,12 +1509,18 @@ namespace Newtonsoft.Json.Serialization allowNonPublicAccess = false; #pragma warning disable 618 if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic) + { allowNonPublicAccess = true; + } #pragma warning restore 618 if (hasMemberAttribute) + { allowNonPublicAccess = true; + } if (memberSerialization == MemberSerialization.Fields) + { allowNonPublicAccess = true; + } } private Predicate CreateShouldSerializeTest(MemberInfo member) @@ -1375,7 +1528,9 @@ namespace Newtonsoft.Json.Serialization MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool)) + { return null; + } MethodCall shouldSerializeCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(shouldSerializeMethod); @@ -1387,7 +1542,9 @@ namespace Newtonsoft.Json.Serialization { MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix); if (specifiedMember == null) + { specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix); + } if (specifiedMember == null || ReflectionUtils.GetMemberUnderlyingType(specifiedMember) != typeof(bool)) { @@ -1399,7 +1556,9 @@ namespace Newtonsoft.Json.Serialization property.GetIsSpecified = o => (bool)specifiedPropertyGet(o); if (ReflectionUtils.CanSetMemberValue(specifiedMember, allowNonPublicAccess, false)) + { property.SetIsSpecified = JsonTypeReflector.ReflectionDelegateFactory.CreateSet(specifiedMember); + } } /// diff --git a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs index 40787992..885ccfc3 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs @@ -38,11 +38,17 @@ namespace Newtonsoft.Json.Serialization JsonSerializerInternalBase internalSerializer; if (context is JsonSerializerInternalBase) + { internalSerializer = (JsonSerializerInternalBase)context; + } else if (context is JsonSerializerProxy) + { internalSerializer = ((JsonSerializerProxy)context).GetInternalSerializer(); + } else + { throw new JsonException("The DefaultReferenceResolver can only be used internally."); + } return internalSerializer.DefaultReferenceMappings; } diff --git a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index b3120ef9..5df55dc2 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -78,11 +78,15 @@ namespace Newtonsoft.Json.Serialization #endif if (assembly == null) + { throw new JsonSerializationException("Could not load assembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, assemblyName)); + } Type type = assembly.GetType(typeName); if (type == null) + { throw new JsonSerializationException("Could not find type '{0}' in assembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, assembly.FullName)); + } return type; } @@ -106,13 +110,15 @@ namespace Newtonsoft.Json.Serialization public override int GetHashCode() { return ((AssemblyName != null) ? AssemblyName.GetHashCode() : 0) - ^ ((TypeName != null) ? TypeName.GetHashCode() : 0); + ^ ((TypeName != null) ? TypeName.GetHashCode() : 0); } public override bool Equals(object obj) { if (!(obj is TypeNameKey)) + { return false; + } return Equals((TypeNameKey)obj); } diff --git a/Src/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs b/Src/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs index 1b3f17b4..72388ba1 100644 --- a/Src/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs @@ -46,7 +46,9 @@ namespace Newtonsoft.Json.Serialization public void Trace(TraceLevel level, string message, Exception ex) { if (level == TraceLevel.Off) + { return; + } TraceEventCache eventCache = new TraceEventCache(); TraceEventType traceEventType = GetTraceEventType(level); @@ -66,7 +68,9 @@ namespace Newtonsoft.Json.Serialization } if (DiagnosticsTrace.AutoFlush) + { listener.Flush(); + } } } } diff --git a/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs b/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs index 6ed4ba2a..211fcc55 100644 --- a/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs +++ b/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs @@ -65,7 +65,9 @@ namespace Newtonsoft.Json.Serialization try { if (_setter == null) + { _setter = DynamicReflectionDelegateFactory.Instance.CreateSet(_memberInfo); + } #if DEBUG // dynamic method doesn't check whether the type is 'legal' to set @@ -73,7 +75,9 @@ namespace Newtonsoft.Json.Serialization if (value == null) { if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo))) + { throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); + } } else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType())) { @@ -99,7 +103,9 @@ namespace Newtonsoft.Json.Serialization try { if (_getter == null) + { _getter = DynamicReflectionDelegateFactory.Instance.CreateGet(_memberInfo); + } return _getter(target); } @@ -110,4 +116,5 @@ namespace Newtonsoft.Json.Serialization } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs b/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs index ebb929e3..81f8f3d6 100644 --- a/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs +++ b/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs @@ -65,7 +65,9 @@ namespace Newtonsoft.Json.Serialization try { if (_setter == null) + { _setter = ExpressionReflectionDelegateFactory.Instance.CreateSet(_memberInfo); + } #if DEBUG // dynamic method doesn't check whether the type is 'legal' to set @@ -73,7 +75,9 @@ namespace Newtonsoft.Json.Serialization if (value == null) { if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo))) + { throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); + } } else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType())) { @@ -99,7 +103,9 @@ namespace Newtonsoft.Json.Serialization try { if (_getter == null) + { _getter = ExpressionReflectionDelegateFactory.Instance.CreateGet(_memberInfo); + } return _getter(target); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs index a60f1491..1dafcb04 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -77,7 +77,9 @@ namespace Newtonsoft.Json.Serialization get { if (_parameterizedCreator == null) + { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); + } return _parameterizedCreator; } @@ -134,15 +136,23 @@ namespace Newtonsoft.Json.Serialization else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) + { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; + } else + { CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); + } if (underlyingType == typeof(IList)) + { CreatedType = typeof(List); + } if (CollectionItemType != null) + { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + } IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; @@ -153,11 +163,15 @@ namespace Newtonsoft.Json.Serialization if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) + { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); + } #if !(NET20 || NET35 || PORTABLE40) if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) + { CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); + } #endif _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); @@ -171,7 +185,9 @@ namespace Newtonsoft.Json.Serialization if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) + { CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); + } _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); @@ -184,7 +200,9 @@ namespace Newtonsoft.Json.Serialization CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) + { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); + } _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); @@ -258,9 +276,13 @@ namespace Newtonsoft.Json.Serialization if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); + } else + { constructorArgument = _genericCollectionDefinitionType; + } ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); diff --git a/Src/Newtonsoft.Json/Serialization/JsonContract.cs b/Src/Newtonsoft.Json/Serialization/JsonContract.cs index 945b528b..c36b500e 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonContract.cs @@ -144,7 +144,9 @@ namespace Newtonsoft.Json.Serialization get { if (_onDeserializedCallbacks == null) + { _onDeserializedCallbacks = new List(); + } return _onDeserializedCallbacks; } @@ -159,7 +161,9 @@ namespace Newtonsoft.Json.Serialization get { if (_onDeserializingCallbacks == null) + { _onDeserializingCallbacks = new List(); + } return _onDeserializingCallbacks; } @@ -174,7 +178,9 @@ namespace Newtonsoft.Json.Serialization get { if (_onSerializedCallbacks == null) + { _onSerializedCallbacks = new List(); + } return _onSerializedCallbacks; } @@ -189,7 +195,9 @@ namespace Newtonsoft.Json.Serialization get { if (_onSerializingCallbacks == null) + { _onSerializingCallbacks = new List(); + } return _onSerializingCallbacks; } @@ -204,7 +212,9 @@ namespace Newtonsoft.Json.Serialization get { if (_onErrorCallbacks == null) + { _onErrorCallbacks = new List(); + } return _onErrorCallbacks; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index 10bfbc7e..ab3829c5 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -91,7 +91,9 @@ namespace Newtonsoft.Json.Serialization get { if (_parameterizedCreator == null) + { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); + } return _parameterizedCreator; } @@ -136,7 +138,9 @@ namespace Newtonsoft.Json.Serialization valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) + { CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); @@ -149,7 +153,9 @@ namespace Newtonsoft.Json.Serialization valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) + { CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); + } IsReadOnlyOrFixedSize = true; } @@ -159,7 +165,9 @@ namespace Newtonsoft.Json.Serialization ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) + { CreatedType = typeof(Dictionary); + } } if (keyType != null && valueType != null) diff --git a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index 2b3d67fe..def59481 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -62,7 +62,9 @@ namespace Newtonsoft.Json.Serialization JToken token = value as JToken; if (token == null) + { throw new ArgumentException("Value is not a JToken.", "value"); + } return _reader.CreateISerializableItem(token, type, _contract, _member); } @@ -72,7 +74,9 @@ namespace Newtonsoft.Json.Serialization ValidationUtils.ArgumentNotNull(value, "value"); if (value is JValue) + { value = ((JValue)value).Value; + } return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs b/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs index 7ac82731..0e8dc09c 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs @@ -51,4 +51,5 @@ namespace Newtonsoft.Json.Serialization } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs b/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs index 8edb688c..1b33569a 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs @@ -200,7 +200,9 @@ namespace Newtonsoft.Json.Serialization { // we should never get here if the environment is not fully trusted, check just in case if (!JsonTypeReflector.FullyTrusted) + { throw new JsonException("Insufficient permissions. Creating an uninitialized '{0}' type requires full trust.".FormatWith(CultureInfo.InvariantCulture, NonNullableUnderlyingType)); + } return FormatterServices.GetUninitializedObject(NonNullableUnderlyingType); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonProperty.cs b/Src/Newtonsoft.Json/Serialization/JsonProperty.cs index 3b7bbe68..6caee7e9 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonProperty.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonProperty.cs @@ -157,7 +157,9 @@ namespace Newtonsoft.Json.Serialization get { if (!_hasExplicitDefaultValue) + { return null; + } return _defaultValue; } @@ -171,7 +173,9 @@ namespace Newtonsoft.Json.Serialization internal object GetResolvedDefaultValue() { if (_propertyType == null) + { return null; + } if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue) { @@ -292,9 +296,13 @@ namespace Newtonsoft.Json.Serialization internal void WritePropertyName(JsonWriter writer) { if (_skipPropertyNameEscape) + { writer.WritePropertyName(PropertyName, false); + } else + { writer.WritePropertyName(PropertyName); + } } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs index 11be9c75..c39f2fa0 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs @@ -69,11 +69,13 @@ namespace Newtonsoft.Json.Serialization // override equality comparer for object key dictionary // object will be modified as it deserializes and might have mutable hashcode if (_mappings == null) + { _mappings = new BidirectionalDictionary( EqualityComparer.Default, new ReferenceEqualsEqualityComparer(), "A different value already has the Id '{0}'.", "A different Id has already been assigned for value '{0}'."); + } return _mappings; } @@ -82,10 +84,14 @@ namespace Newtonsoft.Json.Serialization private ErrorContext GetErrorContext(object currentObject, object member, string path, Exception error) { if (_currentErrorContext == null) + { _currentErrorContext = new ErrorContext(currentObject, member, path, error); + } if (_currentErrorContext.Error != error) + { throw new InvalidOperationException("Current error context error is different to requested error."); + } return _currentErrorContext; } @@ -93,7 +99,9 @@ namespace Newtonsoft.Json.Serialization protected void ClearErrorContext() { if (_currentErrorContext == null) + { throw new InvalidOperationException("Could not clear error context. Error context is already null."); + } _currentErrorContext = null; } @@ -110,22 +118,30 @@ namespace Newtonsoft.Json.Serialization // kind of a hack but meh. might clean this up later string message = (GetType() == typeof(JsonSerializerInternalWriter)) ? "Error serializing" : "Error deserializing"; if (contract != null) + { message += " " + contract.UnderlyingType; + } message += ". " + ex.Message; // add line information to non-json.net exception message if (!(ex is JsonException)) + { message = JsonPosition.FormatMessage(lineInfo, path, message); + } TraceWriter.Trace(TraceLevel.Error, message, ex); } // attribute method is non-static so don't invoke if no object if (contract != null && currentObject != null) + { contract.InvokeOnError(currentObject, Serializer.Context, errorContext); + } if (!errorContext.Handled) + { Serializer.OnError(new ErrorEventArgs(currentObject, errorContext)); + } return errorContext.Handled; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 7c2745c9..05f027c9 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -44,6 +44,7 @@ using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Serialization @@ -213,12 +214,12 @@ namespace Newtonsoft.Json.Serialization if (contract != null) { - if (contract.UnderlyingType == typeof (JRaw)) + if (contract.UnderlyingType == typeof(JRaw)) { return JRaw.Create(reader); } if (reader.TokenType == JsonToken.Null - && !(contract.UnderlyingType == typeof (JValue) || contract.UnderlyingType == typeof (JToken))) + && !(contract.UnderlyingType == typeof(JValue) || contract.UnderlyingType == typeof(JToken))) { return null; } @@ -312,7 +313,7 @@ namespace Newtonsoft.Json.Serialization } // string that needs to be returned as a byte array should be base 64 decoded - if (objectType == typeof (byte[])) + if (objectType == typeof(byte[])) { return Convert.FromBase64String(s); } @@ -325,7 +326,7 @@ namespace Newtonsoft.Json.Serialization case JsonToken.Null: case JsonToken.Undefined: #if !(DOTNET || PORTABLE40 || PORTABLE) - if (objectType == typeof (DBNull)) + if (objectType == typeof(DBNull)) { return DBNull.Value; } @@ -651,7 +652,7 @@ namespace Newtonsoft.Json.Serialization CheckedRead(reader); if (reader.TokenType == JsonToken.PropertyName) { - if ((string) reader.Value == JsonTypeReflector.ValuePropertyName) + if ((string)reader.Value == JsonTypeReflector.ValuePropertyName) { return false; } @@ -809,7 +810,7 @@ namespace Newtonsoft.Json.Serialization if (objectType != null #if !(NET35 || NET20 || PORTABLE40) - && objectType != typeof (IDynamicMetaObjectProvider) + && objectType != typeof(IDynamicMetaObjectProvider) #endif && !objectType.IsAssignableFrom(specifiedType)) { @@ -824,7 +825,9 @@ namespace Newtonsoft.Json.Serialization private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) { if (contract == null) + { throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); + } JsonArrayContract arrayContract = contract as JsonArrayContract; if (arrayContract == null) @@ -1326,7 +1329,7 @@ namespace Newtonsoft.Json.Serialization } JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); - PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract) ? ((JsonPrimitiveContract) contract.KeyContract).TypeCode : PrimitiveTypeCode.Empty; + PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract) ? ((JsonPrimitiveContract)contract.KeyContract).TypeCode : PrimitiveTypeCode.Empty; bool finished = false; do @@ -1788,7 +1791,7 @@ namespace Newtonsoft.Json.Serialization if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer._constructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) { - newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator(); + newObject = (IDynamicMetaObjectProvider)contract.DefaultCreator(); } else { @@ -1815,7 +1818,9 @@ namespace Newtonsoft.Json.Serialization try { if (!reader.Read()) + { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } // first attempt to find a settable property, otherwise fall back to a dynamic set without type JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); @@ -2255,7 +2260,7 @@ namespace Newtonsoft.Json.Serialization { throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, objectContract.UnderlyingType)); } - + throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.".FormatWith(CultureInfo.InvariantCulture, objectContract.UnderlyingType)); } @@ -2469,10 +2474,14 @@ namespace Newtonsoft.Json.Serialization if (!property.Ignored) { if (property.PropertyContract == null) + { property.PropertyContract = GetContractSafe(property.PropertyType); + } if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable) + { property.ValueProvider.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); + } } break; case PropertyPresence.Null: @@ -2514,7 +2523,7 @@ namespace Newtonsoft.Json.Serialization propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value)) ? PropertyPresence.Null : PropertyPresence.Value; - break; + break; case JsonToken.Null: case JsonToken.Undefined: propertyPresence = PropertyPresence.Null; diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index c5c80296..fa3c58d3 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -60,7 +60,9 @@ namespace Newtonsoft.Json.Serialization public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { if (jsonWriter == null) + { throw new ArgumentNullException("jsonWriter"); + } _rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null; _rootLevel = _serializeStack.Count + 1; @@ -104,7 +106,9 @@ namespace Newtonsoft.Json.Serialization private JsonSerializerProxy GetInternalSerializer() { if (InternalSerializer == null) + { InternalSerializer = new JsonSerializerProxy(this); + } return InternalSerializer; } @@ -112,7 +116,9 @@ namespace Newtonsoft.Json.Serialization private JsonContract GetContractSafe(object value) { if (value == null) + { return null; + } return Serializer._contractResolver.ResolveContract(value.GetType()); } @@ -147,7 +153,7 @@ namespace Newtonsoft.Json.Serialization return; } - JsonConverter converter = + JsonConverter converter = ((member != null) ? member.Converter : null) ?? ((containerProperty != null) ? containerProperty.ItemConverter : null) ?? ((containerContract != null) ? containerContract.ItemConverter : null) ?? @@ -169,9 +175,13 @@ namespace Newtonsoft.Json.Serialization case JsonContractType.Array: JsonArrayContract arrayContract = (JsonArrayContract)valueContract; if (!arrayContract.IsMultidimensionalArray) + { SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty); + } else + { SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty); + } break; case JsonContractType.Primitive: SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty); @@ -205,16 +215,24 @@ namespace Newtonsoft.Json.Serialization // value could be coming from a dictionary or array and not have a property if (property != null) + { isReference = property.IsReference; + } if (isReference == null && containerProperty != null) + { isReference = containerProperty.ItemIsReference; + } if (isReference == null && collectionContract != null) + { isReference = collectionContract.ItemIsReference; + } if (isReference == null) + { isReference = contract.IsReference; + } return isReference; } @@ -222,22 +240,32 @@ namespace Newtonsoft.Json.Serialization private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (value == null) + { return false; + } if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) + { return false; + } bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty); if (isReference == null) { if (valueContract.ContractType == JsonContractType.Array) + { isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); + } else + { isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); + } } if (!isReference.Value) + { return false; + } return Serializer.GetReferenceResolver().IsReferenced(this, value); } @@ -246,11 +274,15 @@ namespace Newtonsoft.Json.Serialization { if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && memberValue == null) + { return false; + } if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())) + { return false; + } return true; } @@ -258,18 +290,26 @@ namespace Newtonsoft.Json.Serialization private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) + { return true; + } ReferenceLoopHandling? referenceLoopHandling = null; if (property != null) + { referenceLoopHandling = property.ReferenceLoopHandling; + } if (referenceLoopHandling == null && containerProperty != null) + { referenceLoopHandling = containerProperty.ItemReferenceLoopHandling; + } if (referenceLoopHandling == null && containerContract != null) + { referenceLoopHandling = containerContract.ItemReferenceLoopHandling; + } bool exists = (Serializer._equalityComparer != null) ? _serializeStack.Contains(value, Serializer._equalityComparer) @@ -279,7 +319,9 @@ namespace Newtonsoft.Json.Serialization { string message = "Self referencing loop detected"; if (property != null) + { message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName); + } message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()); switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling)) @@ -288,12 +330,16 @@ namespace Newtonsoft.Json.Serialization throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); case ReferenceLoopHandling.Ignore: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null); + } return false; case ReferenceLoopHandling.Serialize: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null); + } return true; } @@ -307,7 +353,9 @@ namespace Newtonsoft.Json.Serialization string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null); + } writer.WriteStartObject(); writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false); @@ -379,7 +427,9 @@ namespace Newtonsoft.Json.Serialization private void OnSerializing(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } contract.InvokeOnSerializing(value, Serializer._context); } @@ -387,7 +437,9 @@ namespace Newtonsoft.Json.Serialization private void OnSerialized(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); + } contract.InvokeOnSerialized(value, Serializer._context); } @@ -411,7 +463,9 @@ namespace Newtonsoft.Json.Serialization JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) + { continue; + } property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); @@ -419,9 +473,13 @@ namespace Newtonsoft.Json.Serialization catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) + { HandleError(writer, initialDepth); + } else + { throw; + } } } @@ -446,7 +504,9 @@ namespace Newtonsoft.Json.Serialization else { if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member)) + { continue; + } writer.WritePropertyName(propertyName); @@ -468,7 +528,9 @@ namespace Newtonsoft.Json.Serialization if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) + { property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); + } memberValue = property.ValueProvider.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); @@ -483,7 +545,9 @@ namespace Newtonsoft.Json.Serialization } if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) + { return false; + } if (memberValue == null) { @@ -529,7 +593,9 @@ namespace Newtonsoft.Json.Serialization string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null); + } writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false); writer.WriteValue(reference); @@ -540,7 +606,9 @@ namespace Newtonsoft.Json.Serialization string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null); + } writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false); writer.WriteValue(typeName); @@ -570,17 +638,23 @@ namespace Newtonsoft.Json.Serialization else { if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) + { return; + } _serializeStack.Add(value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); + } converter.WriteJson(writer, value, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) + { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); + } _serializeStack.RemoveAt(_serializeStack.Count - 1); } @@ -624,9 +698,13 @@ namespace Newtonsoft.Json.Serialization catch (Exception ex) { if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex)) + { HandleError(writer, initialDepth); + } else + { throw; + } } finally { @@ -637,7 +715,9 @@ namespace Newtonsoft.Json.Serialization writer.WriteEndArray(); if (hasWrittenMetadataObject) + { writer.WriteEndObject(); + } _serializeStack.RemoveAt(_serializeStack.Count - 1); @@ -655,7 +735,9 @@ namespace Newtonsoft.Json.Serialization SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]); if (hasWrittenMetadataObject) + { writer.WriteEndObject(); + } _serializeStack.RemoveAt(_serializeStack.Count - 1); @@ -701,9 +783,13 @@ namespace Newtonsoft.Json.Serialization catch (Exception ex) { if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) + { HandleError(writer, initialDepth + 1); + } else + { throw; + } } } else @@ -740,7 +826,9 @@ namespace Newtonsoft.Json.Serialization } if (contract.ItemContract == null) + { contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); + } return writeMetadataObject; } @@ -814,7 +902,9 @@ namespace Newtonsoft.Json.Serialization JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) + { continue; + } property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); @@ -822,9 +912,13 @@ namespace Newtonsoft.Json.Serialization catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) + { HandleError(writer, initialDepth); + } else + { throw; + } } } } @@ -839,7 +933,9 @@ namespace Newtonsoft.Json.Serialization JsonContract valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) + { continue; + } if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member)) { @@ -854,9 +950,13 @@ namespace Newtonsoft.Json.Serialization catch (Exception ex) { if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex)) + { HandleError(writer, initialDepth); + } else + { throw; + } } } } @@ -871,11 +971,15 @@ namespace Newtonsoft.Json.Serialization private bool ShouldWriteDynamicProperty(object memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) + { return false; + } if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) && (memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType())))) + { return false; + } return true; } @@ -889,7 +993,9 @@ namespace Newtonsoft.Json.Serialization ?? Serializer._typeNameHandling; if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag)) + { return true; + } // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default) if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto)) @@ -897,17 +1003,23 @@ namespace Newtonsoft.Json.Serialization if (member != null) { if (contract.UnderlyingType != member.PropertyContract.CreatedType) + { return true; + } } else if (containerContract != null) { if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType) + { return true; + } } else if (_rootContract != null && _serializeStack.Count == _rootLevel) { if (contract.UnderlyingType != _rootContract.CreatedType) + { return true; + } } } @@ -925,10 +1037,14 @@ namespace Newtonsoft.Json.Serialization WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); if (contract.ItemContract == null) + { contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); + } if (contract.KeyContract == null) + { contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); + } int initialDepth = writer.Top; @@ -954,7 +1070,9 @@ namespace Newtonsoft.Json.Serialization else { if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) + { continue; + } writer.WritePropertyName(propertyName, escape); @@ -964,9 +1082,13 @@ namespace Newtonsoft.Json.Serialization catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) + { HandleError(writer, initialDepth); + } else + { throw; + } } } @@ -1025,7 +1147,9 @@ namespace Newtonsoft.Json.Serialization ClearErrorContext(); if (writer.WriteState == WriteState.Property) + { writer.WriteNull(); + } while (writer.Top > initialDepth) { @@ -1036,12 +1160,16 @@ namespace Newtonsoft.Json.Serialization private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target) { if (property.ShouldSerialize == null) + { return true; + } bool shouldSerialize = property.ShouldSerialize(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null); + } return shouldSerialize; } @@ -1049,12 +1177,16 @@ namespace Newtonsoft.Json.Serialization private bool IsSpecified(JsonWriter writer, JsonProperty property, object target) { if (property.GetIsSpecified == null) + { return true; + } bool isSpecified = property.GetIsSpecified(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + { TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null); + } return isSpecified; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs index 65d4e69e..d63d5670 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs @@ -214,9 +214,13 @@ namespace Newtonsoft.Json.Serialization internal JsonSerializerInternalBase GetInternalSerializer() { if (_serializerReader != null) + { return _serializerReader; + } else + { return _serializerWriter; + } } public JsonSerializerProxy(JsonSerializerInternalReader serializerReader) @@ -238,25 +242,37 @@ namespace Newtonsoft.Json.Serialization internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) + { return _serializerReader.Deserialize(reader, objectType, false); + } else + { return _serializer.Deserialize(reader, objectType); + } } internal override void PopulateInternal(JsonReader reader, object target) { if (_serializerReader != null) + { _serializerReader.Populate(reader, target); + } else + { _serializer.Populate(reader, target); + } } internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) + { _serializerWriter.Serialize(jsonWriter, value, rootType); + } else + { _serializer.Serialize(jsonWriter, value); + } } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index 2d86b89a..f5280a3d 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -56,7 +56,7 @@ namespace Newtonsoft.Json.Serialization public const string ShouldSerializePrefix = "ShouldSerialize"; public const string SpecifiedPostfix = "Specified"; - private static readonly ThreadSafeStore> JsonConverterCreatorCache = + private static readonly ThreadSafeStore> JsonConverterCreatorCache = new ThreadSafeStore>(GetJsonConverterCreator); #if !(NET20 || DOTNET) @@ -79,7 +79,9 @@ namespace Newtonsoft.Json.Serialization { DataContractAttribute result = CachedAttributeGetter.GetAttribute(currentType); if (result != null) + { return result; + } currentType = currentType.BaseType(); } @@ -93,7 +95,9 @@ namespace Newtonsoft.Json.Serialization // can't override a field if (memberInfo.MemberType() == MemberTypes.Field) + { return CachedAttributeGetter.GetAttribute(memberInfo); + } // search property and then search base properties if nothing is returned and the property is virtual PropertyInfo propertyInfo = (PropertyInfo)memberInfo; @@ -108,7 +112,9 @@ namespace Newtonsoft.Json.Serialization { PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); if (baseProperty != null && baseProperty.IsVirtual()) + { result = CachedAttributeGetter.GetAttribute(baseProperty); + } currentType = currentType.BaseType(); } @@ -123,12 +129,16 @@ namespace Newtonsoft.Json.Serialization { JsonObjectAttribute objectAttribute = GetCachedAttribute(objectType); if (objectAttribute != null) + { return objectAttribute.MemberSerialization; + } #if !NET20 DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType); if (dataContractAttribute != null) + { return MemberSerialization.OptIn; + } #endif #if !(DOTNET || PORTABLE40 || PORTABLE) @@ -136,7 +146,9 @@ namespace Newtonsoft.Json.Serialization { SerializableAttribute serializableAttribute = GetCachedAttribute(objectType); if (serializableAttribute != null) + { return MemberSerialization.Fields; + } } #endif @@ -152,7 +164,9 @@ namespace Newtonsoft.Json.Serialization { Func creator = JsonConverterCreatorCache.Get(converterAttribute.ConverterType); if (creator != null) + { return creator(converterAttribute.ConverterParameters); + } } return null; @@ -196,14 +210,16 @@ namespace Newtonsoft.Json.Serialization parameterizedConstructor = ReflectionDelegateFactory.CreateParameterizedConstructor(parameterizedConstructorInfo); return (JsonConverter)parameterizedConstructor(parameters); } - else + else { throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType)); - } + } } if (defaultConstructor == null) + { throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType)); + } return (JsonConverter)defaultConstructor(); } @@ -242,7 +258,9 @@ namespace Newtonsoft.Json.Serialization const string metadataClassTypeName = "MetadataClassType"; if (_metadataTypeAttributeReflectionObject == null) + { _metadataTypeAttributeReflectionObject = ReflectionObject.Create(attributeType, metadataClassTypeName); + } return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName); } @@ -262,19 +280,25 @@ namespace Newtonsoft.Json.Serialization { attribute = ReflectionUtils.GetAttribute(metadataType, true); if (attribute != null) + { return attribute; + } } #endif attribute = ReflectionUtils.GetAttribute(type, true); if (attribute != null) + { return attribute; + } foreach (Type typeInterface in type.GetInterfaces()) { attribute = ReflectionUtils.GetAttribute(typeInterface, true); if (attribute != null) + { return attribute; + } } return null; @@ -294,14 +318,18 @@ namespace Newtonsoft.Json.Serialization { attribute = ReflectionUtils.GetAttribute(metadataTypeMemberInfo, true); if (attribute != null) + { return attribute; + } } } #endif attribute = ReflectionUtils.GetAttribute(memberInfo, true); if (attribute != null) + { return attribute; + } if (memberInfo.DeclaringType != null) { @@ -313,7 +341,9 @@ namespace Newtonsoft.Json.Serialization { attribute = ReflectionUtils.GetAttribute(interfaceTypeMemberInfo, true); if (attribute != null) + { return attribute; + } } } } @@ -325,11 +355,15 @@ namespace Newtonsoft.Json.Serialization { Type type = provider as Type; if (type != null) + { return GetAttribute(type); + } MemberInfo memberInfo = provider as MemberInfo; if (memberInfo != null) + { return GetAttribute(memberInfo); + } return ReflectionUtils.GetAttribute(provider, true); } @@ -413,7 +447,9 @@ namespace Newtonsoft.Json.Serialization { #if !(PORTABLE40 || PORTABLE || DOTNET) if (DynamicCodeGeneration) + { return DynamicReflectionDelegateFactory.Instance; + } return LateBoundReflectionDelegateFactory.Instance; #else diff --git a/Src/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs b/Src/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs index 093c34cb..7581216b 100644 --- a/Src/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs @@ -42,7 +42,9 @@ namespace Newtonsoft.Json.Serialization public void Trace(TraceLevel level, string message, Exception ex) { if (_traceMessages.Count >= 1000) + { _traceMessages.Dequeue(); + } StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture)); @@ -75,7 +77,9 @@ namespace Newtonsoft.Json.Serialization foreach (string traceMessage in _traceMessages) { if (sb.Length > 0) + { sb.AppendLine(); + } sb.Append(traceMessage); } diff --git a/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs b/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs index 5867e7ab..1826fe49 100644 --- a/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs +++ b/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs @@ -48,16 +48,24 @@ namespace Newtonsoft.Json.Utilities public void Encode(byte[] buffer, int index, int count) { if (buffer == null) + { throw new ArgumentNullException("buffer"); + } if (index < 0) + { throw new ArgumentOutOfRangeException("index"); + } if (count < 0) + { throw new ArgumentOutOfRangeException("count"); + } if (count > (buffer.Length - index)) + { throw new ArgumentOutOfRangeException("count"); + } if (_leftOverBytesCount > 0) { diff --git a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs index 2711adf7..b72d56cc 100644 --- a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs +++ b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs @@ -67,13 +67,17 @@ namespace Newtonsoft.Json.Utilities if (_firstToSecond.TryGetValue(first, out existingSecond)) { if (!existingSecond.Equals(second)) + { throw new ArgumentException(_duplicateFirstErrorMessage.FormatWith(CultureInfo.InvariantCulture, first)); + } } if (_secondToFirst.TryGetValue(second, out existingFirst)) { if (!existingFirst.Equals(first)) + { throw new ArgumentException(_duplicateSecondErrorMessage.FormatWith(CultureInfo.InvariantCulture, second)); + } } _firstToSecond.Add(first, second); diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index ca755bf2..f064839a 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -65,10 +65,14 @@ namespace Newtonsoft.Json.Utilities public static void AddRange(this IList initial, IEnumerable collection) { if (initial == null) + { throw new ArgumentNullException("initial"); + } if (collection == null) + { return; + } foreach (T value in collection) { @@ -91,12 +95,18 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(type, "type"); if (typeof(IDictionary).IsAssignableFrom(type)) + { return true; + } if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>))) + { return true; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IReadOnlyDictionary<,>))) + { return true; + } #endif return false; @@ -142,7 +152,9 @@ namespace Newtonsoft.Json.Utilities public static bool AddDistinct(this IList list, T value, IEqualityComparer comparer) { if (list.ContainsValue(value, comparer)) + { return false; + } list.Add(value); return true; @@ -152,15 +164,21 @@ namespace Newtonsoft.Json.Utilities public static bool ContainsValue(this IEnumerable source, TSource value, IEqualityComparer comparer) { if (comparer == null) + { comparer = EqualityComparer.Default; + } if (source == null) + { throw new ArgumentNullException("source"); + } foreach (TSource local in source) { if (comparer.Equals(local, value)) + { return true; + } } return false; @@ -172,7 +190,9 @@ namespace Newtonsoft.Json.Utilities foreach (T value in values) { if (!list.AddDistinct(value, comparer)) + { allAdded = false; + } } return allAdded; @@ -184,7 +204,9 @@ namespace Newtonsoft.Json.Utilities foreach (T value in collection) { if (predicate(value)) + { return index; + } index++; } @@ -237,16 +259,24 @@ namespace Newtonsoft.Json.Utilities // don't keep calculating dimensions for arrays inside the value array if (dimensions.Count == dimensionsCount) + { break; + } if (currentArray.Count == 0) + { break; + } object v = currentArray[0]; if (v is IList) + { currentArray = (IList)v; + } else + { break; + } } return dimensions; @@ -265,7 +295,9 @@ namespace Newtonsoft.Json.Utilities IList list = (IList)JaggedArrayGetValue(values, indices); int currentValuesLength = list.Count; if (currentValuesLength != dimensionLength) + { throw new Exception("Cannot deserialize non-cubical array as multidimensional array."); + } int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) @@ -287,9 +319,13 @@ namespace Newtonsoft.Json.Utilities { int index = indices[i]; if (i == indices.Length - 1) + { return currentList[index]; + } else + { currentList = (IList)currentList[index]; + } } return currentList; } diff --git a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs index 2497845f..6268b011 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -53,9 +53,13 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(list, "list"); if (list is ICollection) + { _genericCollection = (ICollection)list; + } else + { _list = list; + } } public CollectionWrapper(ICollection list) @@ -68,33 +72,49 @@ namespace Newtonsoft.Json.Utilities public virtual void Add(T item) { if (_genericCollection != null) + { _genericCollection.Add(item); + } else + { _list.Add(item); + } } public virtual void Clear() { if (_genericCollection != null) + { _genericCollection.Clear(); + } else + { _list.Clear(); + } } public virtual bool Contains(T item) { if (_genericCollection != null) + { return _genericCollection.Contains(item); + } else + { return _list.Contains(item); + } } public virtual void CopyTo(T[] array, int arrayIndex) { if (_genericCollection != null) + { _genericCollection.CopyTo(array, arrayIndex); + } else + { _list.CopyTo(array, arrayIndex); + } } public virtual int Count @@ -102,9 +122,13 @@ namespace Newtonsoft.Json.Utilities get { if (_genericCollection != null) + { return _genericCollection.Count; + } else + { return _list.Count; + } } } @@ -113,9 +137,13 @@ namespace Newtonsoft.Json.Utilities get { if (_genericCollection != null) + { return _genericCollection.IsReadOnly; + } else + { return _list.IsReadOnly; + } } } @@ -130,7 +158,9 @@ namespace Newtonsoft.Json.Utilities bool contains = _list.Contains(item); if (contains) + { _list.Remove(item); + } return contains; } @@ -139,7 +169,9 @@ namespace Newtonsoft.Json.Utilities public virtual IEnumerator GetEnumerator() { if (_genericCollection != null) + { return _genericCollection.GetEnumerator(); + } return _list.Cast().GetEnumerator(); } @@ -147,9 +179,13 @@ namespace Newtonsoft.Json.Utilities IEnumerator IEnumerable.GetEnumerator() { if (_genericCollection != null) + { return _genericCollection.GetEnumerator(); + } else + { return _list.GetEnumerator(); + } } int IList.Add(object value) @@ -163,7 +199,9 @@ namespace Newtonsoft.Json.Utilities bool IList.Contains(object value) { if (IsCompatibleObject(value)) + { return Contains((T)value); + } return false; } @@ -171,10 +209,14 @@ namespace Newtonsoft.Json.Utilities int IList.IndexOf(object value) { if (_genericCollection != null) + { throw new InvalidOperationException("Wrapped ICollection does not support IndexOf."); + } if (IsCompatibleObject(value)) + { return _list.IndexOf((T)value); + } return -1; } @@ -182,7 +224,9 @@ namespace Newtonsoft.Json.Utilities void IList.RemoveAt(int index) { if (_genericCollection != null) + { throw new InvalidOperationException("Wrapped ICollection does not support RemoveAt."); + } _list.RemoveAt(index); } @@ -190,7 +234,9 @@ namespace Newtonsoft.Json.Utilities void IList.Insert(int index, object value) { if (_genericCollection != null) + { throw new InvalidOperationException("Wrapped ICollection does not support Insert."); + } VerifyValueType(value); _list.Insert(index, (T)value); @@ -201,17 +247,23 @@ namespace Newtonsoft.Json.Utilities get { if (_genericCollection != null) + { // ICollection only has IsReadOnly return _genericCollection.IsReadOnly; + } else + { return _list.IsFixedSize; + } } } void IList.Remove(object value) { if (IsCompatibleObject(value)) + { Remove((T)value); + } } object IList.this[int index] @@ -219,14 +271,18 @@ namespace Newtonsoft.Json.Utilities get { if (_genericCollection != null) + { throw new InvalidOperationException("Wrapped ICollection does not support indexer."); + } return _list[index]; } set { if (_genericCollection != null) + { throw new InvalidOperationException("Wrapped ICollection does not support indexer."); + } VerifyValueType(value); _list[index] = (T)value; @@ -248,7 +304,9 @@ namespace Newtonsoft.Json.Utilities get { if (_syncRoot == null) + { Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } return _syncRoot; } @@ -257,13 +315,17 @@ namespace Newtonsoft.Json.Utilities private static void VerifyValueType(object value) { if (!IsCompatibleObject(value)) + { throw new ArgumentException("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.".FormatWith(CultureInfo.InvariantCulture, value, typeof(T)), "value"); + } } private static bool IsCompatibleObject(object value) { if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T))))) + { return false; + } return true; } @@ -273,9 +335,13 @@ namespace Newtonsoft.Json.Utilities get { if (_genericCollection != null) + { return _genericCollection; + } else + { return _list; + } } } } diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 8f05675e..c5e04bf9 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -39,6 +39,7 @@ using Newtonsoft.Json.Utilities.LinqBridge; #endif #if !(DOTNET || PORTABLE40 || PORTABLE) using System.Data.SqlTypes; + #endif namespace Newtonsoft.Json.Utilities @@ -276,7 +277,9 @@ namespace Newtonsoft.Json.Utilities public override bool Equals(object obj) { if (!(obj is TypeConvertKey)) + { return false; + } return Equals((TypeConvertKey)obj); } @@ -294,10 +297,14 @@ namespace Newtonsoft.Json.Utilities { MethodInfo castMethodInfo = t.TargetType.GetMethod("op_Implicit", new[] { t.InitialType }); if (castMethodInfo == null) + { castMethodInfo = t.TargetType.GetMethod("op_Explicit", new[] { t.InitialType }); + } if (castMethodInfo == null) + { return null; + } MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(castMethodInfo); @@ -308,25 +315,45 @@ namespace Newtonsoft.Json.Utilities internal static BigInteger ToBigInteger(object value) { if (value is BigInteger) + { return (BigInteger)value; + } if (value is string) + { return BigInteger.Parse((string)value, CultureInfo.InvariantCulture); + } if (value is float) + { return new BigInteger((float)value); + } if (value is double) + { return new BigInteger((double)value); + } if (value is decimal) + { return new BigInteger((decimal)value); + } if (value is int) + { return new BigInteger((int)value); + } if (value is long) + { return new BigInteger((long)value); + } if (value is uint) + { return new BigInteger((uint)value); + } if (value is ulong) + { return new BigInteger((ulong)value); + } if (value is byte[]) + { return new BigInteger((byte[])value); + } throw new InvalidCastException("Cannot convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } @@ -334,13 +361,21 @@ namespace Newtonsoft.Json.Utilities public static object FromBigInteger(BigInteger i, Type targetType) { if (targetType == typeof(decimal)) + { return (decimal)i; + } if (targetType == typeof(double)) + { return (double)i; + } if (targetType == typeof(float)) + { return (float)i; + } if (targetType == typeof(ulong)) + { return (ulong)i; + } try { @@ -353,7 +388,7 @@ namespace Newtonsoft.Json.Utilities } #endif -#region TryConvert + #region TryConvert internal enum ConvertResult { Success = 0, @@ -385,7 +420,9 @@ namespace Newtonsoft.Json.Utilities try { if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success) + { return true; + } value = null; return false; @@ -400,10 +437,14 @@ namespace Newtonsoft.Json.Utilities private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value) { if (initialValue == null) + { throw new ArgumentNullException("initialValue"); + } if (ReflectionUtils.IsNullableType(targetType)) + { targetType = Nullable.GetUnderlyingType(targetType); + } Type initialType = initialValue.GetType(); @@ -558,9 +599,9 @@ namespace Newtonsoft.Json.Utilities value = null; return ConvertResult.NoValidConversion; } -#endregion + #endregion -#region ConvertOrCast + #region ConvertOrCast /// /// Converts the value to the specified type. If the value is unable to be converted, the /// value is checked whether it assignable to the specified type. @@ -577,17 +618,23 @@ namespace Newtonsoft.Json.Utilities object convertedValue; if (targetType == typeof(object)) + { return initialValue; + } if (initialValue == null && ReflectionUtils.IsNullable(targetType)) + { return null; + } if (TryConvert(initialValue, culture, targetType, out convertedValue)) + { return convertedValue; + } return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); } -#endregion + #endregion private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { @@ -596,16 +643,22 @@ namespace Newtonsoft.Json.Utilities if (value != null) { if (targetType.IsAssignableFrom(valueType)) + { return value; + } Func castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType)); if (castConverter != null) + { return castConverter(value); + } } else { if (ReflectionUtils.IsNullable(targetType)) + { return null; + } } throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); @@ -615,17 +668,29 @@ namespace Newtonsoft.Json.Utilities public static object ToValue(INullable nullableValue) { if (nullableValue == null) + { return null; + } else if (nullableValue is SqlInt32) + { return ToValue((SqlInt32)nullableValue); + } else if (nullableValue is SqlInt64) + { return ToValue((SqlInt64)nullableValue); + } else if (nullableValue is SqlBoolean) + { return ToValue((SqlBoolean)nullableValue); + } else if (nullableValue is SqlString) + { return ToValue((SqlString)nullableValue); + } else if (nullableValue is SqlDateTime) + { return ToValue((SqlDateTime)nullableValue); + } throw new ArgumentException("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType())); } @@ -643,7 +708,7 @@ namespace Newtonsoft.Json.Utilities #if !(NET20 || NET35) return Version.TryParse(input, out result); #else - // improve failure performance with regex? + // improve failure performance with regex? try { result = new Version(input); @@ -680,7 +745,9 @@ namespace Newtonsoft.Json.Utilities value = 0; if (length == 0) + { return ParseResult.Invalid; + } bool isNegative = (chars[start] == '-'); @@ -688,7 +755,9 @@ namespace Newtonsoft.Json.Utilities { // text just a negative sign if (length == 1) + { return ParseResult.Invalid; + } start++; length--; @@ -707,7 +776,9 @@ namespace Newtonsoft.Json.Utilities int c = chars[i] - '0'; if (c < 0 || c > 9) + { return ParseResult.Invalid; + } } return ParseResult.Overflow; @@ -718,7 +789,9 @@ namespace Newtonsoft.Json.Utilities int c = chars[i] - '0'; if (c < 0 || c > 9) + { return ParseResult.Invalid; + } int newValue = (10 * value) - c; @@ -734,7 +807,9 @@ namespace Newtonsoft.Json.Utilities c = chars[i] - '0'; if (c < 0 || c > 9) + { return ParseResult.Invalid; + } } return ParseResult.Overflow; @@ -749,7 +824,9 @@ namespace Newtonsoft.Json.Utilities { // negative integer can be one bigger than positive if (value == int.MinValue) + { return ParseResult.Overflow; + } value = -value; } @@ -762,7 +839,9 @@ namespace Newtonsoft.Json.Utilities value = 0; if (length == 0) + { return ParseResult.Invalid; + } bool isNegative = (chars[start] == '-'); @@ -770,7 +849,9 @@ namespace Newtonsoft.Json.Utilities { // text just a negative sign if (length == 1) + { return ParseResult.Invalid; + } start++; length--; @@ -787,7 +868,9 @@ namespace Newtonsoft.Json.Utilities int c = chars[i] - '0'; if (c < 0 || c > 9) + { return ParseResult.Invalid; + } } return ParseResult.Overflow; @@ -798,7 +881,9 @@ namespace Newtonsoft.Json.Utilities int c = chars[i] - '0'; if (c < 0 || c > 9) + { return ParseResult.Invalid; + } long newValue = (10 * value) - c; @@ -814,7 +899,9 @@ namespace Newtonsoft.Json.Utilities c = chars[i] - '0'; if (c < 0 || c > 9) + { return ParseResult.Invalid; + } } return ParseResult.Overflow; @@ -829,7 +916,9 @@ namespace Newtonsoft.Json.Utilities { // negative integer can be one bigger than positive if (value == long.MinValue) + { return ParseResult.Overflow; + } value = -value; } diff --git a/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs b/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs index 3cea0829..097bfe69 100644 --- a/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DateTimeUtils.cs @@ -196,7 +196,6 @@ namespace Newtonsoft.Json.Utilities } #region Parse - internal static bool TryParseDateTimeIso(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt) { DateTimeParser dateTimeParser = new DateTimeParser(); @@ -228,7 +227,9 @@ namespace Newtonsoft.Json.Utilities { ticks += d.GetUtcOffset().Ticks; if (ticks > DateTime.MaxValue.Ticks) + { ticks = DateTime.MaxValue.Ticks; + } d = new DateTime(ticks, DateTimeKind.Local); } @@ -246,7 +247,9 @@ namespace Newtonsoft.Json.Utilities { ticks += d.GetUtcOffset().Ticks; if (ticks < DateTime.MinValue.Ticks) + { ticks = DateTime.MinValue.Ticks; + } d = new DateTime(ticks, DateTimeKind.Local); } @@ -449,9 +452,11 @@ namespace Newtonsoft.Json.Utilities else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T') { if (DateTimeOffset.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt)) - if (TryParseDateTimeOffsetIso(new StringReference(s.ToCharArray(), 0, s.Length), out dt)) { - return true; + if (TryParseDateTimeOffsetIso(new StringReference(s.ToCharArray(), 0, s.Length), out dt)) + { + return true; + } } } @@ -476,7 +481,9 @@ namespace Newtonsoft.Json.Utilities int index = text.IndexOf('+', 7, text.Length - 8); if (index == -1) + { index = text.IndexOf('-', 7, text.Length - 8); + } if (index != -1) { @@ -642,7 +649,9 @@ namespace Newtonsoft.Json.Utilities { case DateTimeKind.Unspecified: if (value != DateTime.MaxValue && value != DateTime.MinValue) + { pos = WriteDateTimeOffset(chars, pos, o, format); + } break; case DateTimeKind.Local: pos = WriteDateTimeOffset(chars, pos, o, format); @@ -729,7 +738,9 @@ namespace Newtonsoft.Json.Utilities start += 2; if (format == DateFormatHandling.IsoDateFormat) + { chars[start++] = ':'; + } int absMinutes = Math.Abs(offset.Minutes); CopyIntToCharArray(chars, start, absMinutes, 2); @@ -769,7 +780,9 @@ namespace Newtonsoft.Json.Utilities int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) + { y100 = 3; + } // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period @@ -780,7 +793,9 @@ namespace Newtonsoft.Json.Utilities int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) + { y1 = 3; + } year = y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1; diff --git a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index 457d40e0..2c44aa36 100644 --- a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -77,23 +77,35 @@ namespace Newtonsoft.Json.Utilities public void Add(TKey key, TValue value) { if (_dictionary != null) + { _dictionary.Add(key, value); + } else if (_genericDictionary != null) + { _genericDictionary.Add(key, value); + } else + { throw new NotSupportedException(); + } } public bool ContainsKey(TKey key) { if (_dictionary != null) + { return _dictionary.Contains(key); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.ContainsKey(key); + } #endif else + { return _genericDictionary.ContainsKey(key); + } } public ICollection Keys @@ -101,13 +113,19 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary.Keys.Cast().ToList(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.Keys.ToList(); + } #endif else + { return _genericDictionary.Keys; + } } } @@ -169,13 +187,19 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary.Values.Cast().ToList(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.Values.ToList(); + } #endif else + { return _genericDictionary.Values; + } } } @@ -184,61 +208,91 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return (TValue)_dictionary[key]; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary[key]; + } #endif else + { return _genericDictionary[key]; + } } set { if (_dictionary != null) + { _dictionary[key] = value; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else + { _genericDictionary[key] = value; + } } } public void Add(KeyValuePair item) { if (_dictionary != null) + { ((IList)_dictionary).Add(item); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else if (_genericDictionary != null) + { _genericDictionary.Add(item); + } } public void Clear() { if (_dictionary != null) + { _dictionary.Clear(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else + { _genericDictionary.Clear(); + } } public bool Contains(KeyValuePair item) { if (_dictionary != null) + { return ((IList)_dictionary).Contains(item); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.Contains(item); + } #endif else + { return _genericDictionary.Contains(item); + } } public void CopyTo(KeyValuePair[] array, int arrayIndex) @@ -267,13 +321,19 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary.Count; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.Count; + } #endif else + { return _genericDictionary.Count; + } } } @@ -282,13 +342,19 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary.IsReadOnly; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return true; + } #endif else + { return _genericDictionary.IsReadOnly; + } } } @@ -330,13 +396,19 @@ namespace Newtonsoft.Json.Utilities public IEnumerator> GetEnumerator() { if (_dictionary != null) + { return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.GetEnumerator(); + } #endif else + { return _genericDictionary.GetEnumerator(); + } } IEnumerator IEnumerable.GetEnumerator() @@ -347,13 +419,19 @@ namespace Newtonsoft.Json.Utilities void IDictionary.Add(object key, object value) { if (_dictionary != null) + { _dictionary.Add(key, value); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else + { _genericDictionary.Add((TKey)key, (TValue)value); + } } object IDictionary.this[object key] @@ -361,24 +439,36 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary[key]; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary[(TKey)key]; + } #endif else + { return _genericDictionary[(TKey)key]; + } } set { if (_dictionary != null) + { _dictionary[key] = value; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else + { _genericDictionary[(TKey)key] = (TValue)value; + } } } @@ -426,25 +516,37 @@ namespace Newtonsoft.Json.Utilities IDictionaryEnumerator IDictionary.GetEnumerator() { if (_dictionary != null) + { return _dictionary.GetEnumerator(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return new DictionaryEnumerator(_readOnlyDictionary.GetEnumerator()); + } #endif else + { return new DictionaryEnumerator(_genericDictionary.GetEnumerator()); + } } bool IDictionary.Contains(object key) { if (_genericDictionary != null) + { return _genericDictionary.ContainsKey((TKey)key); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.ContainsKey((TKey)key); + } #endif else + { return _dictionary.Contains(key); + } } bool IDictionary.IsFixedSize @@ -452,13 +554,19 @@ namespace Newtonsoft.Json.Utilities get { if (_genericDictionary != null) + { return false; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return true; + } #endif else + { return _dictionary.IsFixedSize; + } } } @@ -467,26 +575,38 @@ namespace Newtonsoft.Json.Utilities get { if (_genericDictionary != null) + { return _genericDictionary.Keys.ToList(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.Keys.ToList(); + } #endif else + { return _dictionary.Keys; + } } } public void Remove(object key) { if (_dictionary != null) + { _dictionary.Remove(key); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else + { _genericDictionary.Remove((TKey)key); + } } ICollection IDictionary.Values @@ -494,26 +614,38 @@ namespace Newtonsoft.Json.Utilities get { if (_genericDictionary != null) + { return _genericDictionary.Values.ToList(); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary.Values.ToList(); + } #endif else + { return _dictionary.Values; + } } } void ICollection.CopyTo(Array array, int index) { if (_dictionary != null) + { _dictionary.CopyTo(array, index); + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { throw new NotSupportedException(); + } #endif else + { _genericDictionary.CopyTo((KeyValuePair[])array, index); + } } bool ICollection.IsSynchronized @@ -521,9 +653,13 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary.IsSynchronized; + } else + { return false; + } } } @@ -532,7 +668,9 @@ namespace Newtonsoft.Json.Utilities get { if (_syncRoot == null) + { Interlocked.CompareExchange(ref _syncRoot, new object(), null); + } return _syncRoot; } @@ -543,13 +681,19 @@ namespace Newtonsoft.Json.Utilities get { if (_dictionary != null) + { return _dictionary; + } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (_readOnlyDictionary != null) + { return _readOnlyDictionary; + } #endif else + { return _genericDictionary; + } } } } diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index b326899e..28321d55 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -76,7 +76,6 @@ namespace Newtonsoft.Json.Utilities : base.BindDeleteMember(binder); } - public override DynamicMetaObject BindConvert(ConvertBinder binder) { return IsOverridden("TryConvert") @@ -87,7 +86,9 @@ namespace Newtonsoft.Json.Utilities public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { if (!IsOverridden("TryInvokeMember")) + { return base.BindInvokeMember(binder, args); + } // // Generate a tree like: @@ -124,7 +125,6 @@ namespace Newtonsoft.Json.Utilities return _dontFallbackFirst ? call : fallback(call); } - public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { return IsOverridden("TryCreateInstance") @@ -201,7 +201,9 @@ namespace Newtonsoft.Json.Utilities { Type t = binder.GetType(); while (!t.IsVisible()) + { t = t.BaseType(); + } return Expression.Constant(binder, t); } @@ -260,7 +262,9 @@ namespace Newtonsoft.Json.Utilities } if (fallbackInvoke != null) + { resultMetaObject = fallbackInvoke(resultMetaObject); + } DynamicMetaObject callDynamic = new DynamicMetaObject( Expression.Block( diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index 4aaded13..13cfe7b0 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -86,7 +86,9 @@ namespace Newtonsoft.Json.Utilities generator.MarkLabel(argsOk); if (!method.IsConstructor && !method.IsStatic) + { generator.PushInstance(method.DeclaringType); + } int localVariableCount = 0; @@ -167,7 +169,7 @@ namespace Newtonsoft.Json.Utilities generator.MarkLabel(finishedProcessingParameter); localVariableCount++; } - else + else { generator.PushArrayInstance(argsIndex, i); @@ -176,18 +178,26 @@ namespace Newtonsoft.Json.Utilities } if (method.IsConstructor) + { generator.Emit(OpCodes.Newobj, (ConstructorInfo)method); + } else + { generator.CallMethod((MethodInfo)method); + } Type returnType = method.IsConstructor ? method.DeclaringType : ((MethodInfo)method).ReturnType; if (returnType != typeof(void)) + { generator.BoxIfNeeded(returnType); + } else + { generator.Emit(OpCodes.Ldnull); + } generator.Return(); } @@ -218,7 +228,9 @@ namespace Newtonsoft.Json.Utilities ReflectionUtils.EmptyTypes, null); if (constructorInfo == null) + { throw new ArgumentException("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); + } generator.Emit(OpCodes.Newobj, constructorInfo); } @@ -240,10 +252,14 @@ namespace Newtonsoft.Json.Utilities { MethodInfo getMethod = propertyInfo.GetGetMethod(true); if (getMethod == null) + { throw new ArgumentException("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); + } if (!getMethod.IsStatic) + { generator.PushInstance(propertyInfo.DeclaringType); + } generator.CallMethod(getMethod); generator.BoxIfNeeded(propertyInfo.PropertyType); @@ -296,15 +312,21 @@ namespace Newtonsoft.Json.Utilities internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator) { if (!fieldInfo.IsStatic) + { generator.PushInstance(fieldInfo.DeclaringType); + } generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(fieldInfo.FieldType); if (!fieldInfo.IsStatic) + { generator.Emit(OpCodes.Stfld, fieldInfo); + } else + { generator.Emit(OpCodes.Stsfld, fieldInfo); + } generator.Return(); } @@ -323,7 +345,9 @@ namespace Newtonsoft.Json.Utilities { MethodInfo setMethod = propertyInfo.GetSetMethod(true); if (!setMethod.IsStatic) + { generator.PushInstance(propertyInfo.DeclaringType); + } generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(propertyInfo.PropertyType); @@ -332,4 +356,5 @@ namespace Newtonsoft.Json.Utilities } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs index a40bd611..a83d311b 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -65,7 +65,9 @@ namespace Newtonsoft.Json.Utilities { Type binderType = Type.GetType(BinderTypeName, false); if (binderType == null) + { throw new InvalidOperationException("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName)); + } // None _getCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0); @@ -196,7 +198,9 @@ namespace Newtonsoft.Json.Utilities { // if the result of a test is to throw an error, rewrite to result an error result value if (node.IfFalse.NodeType == ExpressionType.Throw) + { return Expression.Condition(node.Test, node.IfTrue, Expression.Constant(ErrorResult)); + } return base.VisitConditional(node); } diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index 09b168e9..1cfd7bf2 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -62,7 +62,9 @@ namespace Newtonsoft.Json.Utilities string s; if (map.TryGetBySecond(n2, out s)) + { throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'.".FormatWith(CultureInfo.InvariantCulture, n2, type.Name)); + } map.Set(n1, n2); } @@ -75,7 +77,9 @@ namespace Newtonsoft.Json.Utilities Type enumType = typeof(T); if (!enumType.IsDefined(typeof(FlagsAttribute), false)) + { throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType)); + } Type underlyingType = Enum.GetUnderlyingType(value.GetType()); @@ -86,11 +90,15 @@ namespace Newtonsoft.Json.Utilities foreach (EnumValue enumNameValue in enumNameValues) { if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0) + { selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture)); + } } if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null) + { selectedFlagsValues.Add(default(T)); + } return selectedFlagsValues; } @@ -112,7 +120,9 @@ namespace Newtonsoft.Json.Utilities public static IList> GetNamesAndValues(Type enumType) where TUnderlyingType : struct { if (enumType == null) + { throw new ArgumentNullException("enumType"); + } ValidationUtils.ArgumentTypeIsEnum(enumType, "enumType"); @@ -141,7 +151,9 @@ namespace Newtonsoft.Json.Utilities public static IList GetValues(Type enumType) { if (!enumType.IsEnum()) + { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); + } List values = new List(); @@ -159,7 +171,9 @@ namespace Newtonsoft.Json.Utilities public static IList GetNames(Type enumType) { if (!enumType.IsEnum()) + { throw new ArgumentException("Type '" + enumType.Name + "' is not an enum."); + } List values = new List(); @@ -176,7 +190,9 @@ namespace Newtonsoft.Json.Utilities public static object ParseEnumName(string enumText, bool isNullable, Type t) { if (enumText == string.Empty && isNullable) + { return null; + } string finalEnumText; @@ -215,7 +231,9 @@ namespace Newtonsoft.Json.Utilities resolvedEnumName = resolvedEnumName ?? name; if (camelCaseText) + { resolvedEnumName = StringUtils.ToCamelCase(resolvedEnumName); + } names[i] = resolvedEnumName; } diff --git a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index 0e56ca33..e87a93bb 100644 --- a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -137,26 +137,30 @@ namespace Newtonsoft.Json.Utilities Expression callExpression; if (method.IsConstructor) { - callExpression = Expression.New((ConstructorInfo) method, argsExpression); + callExpression = Expression.New((ConstructorInfo)method, argsExpression); } else if (method.IsStatic) { - callExpression = Expression.Call((MethodInfo) method, argsExpression); + callExpression = Expression.Call((MethodInfo)method, argsExpression); } else { Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType); - callExpression = Expression.Call(readParameter, (MethodInfo) method, argsExpression); + callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } if (method is MethodInfo) { - MethodInfo m = (MethodInfo) method; - if (m.ReturnType != typeof (void)) + MethodInfo m = (MethodInfo)method; + if (m.ReturnType != typeof(void)) + { callExpression = EnsureCastExpression(callExpression, type); + } else + { callExpression = Expression.Block(callExpression, Expression.Constant(null)); + } } else { @@ -170,7 +174,9 @@ namespace Newtonsoft.Json.Utilities foreach (ByRefParameter p in refParameterMap) { if (!p.IsOut) + { bodyExpressions.Add(Expression.Assign(p.Variable, p.Value)); + } variableExpressions.Add(p.Variable); } @@ -189,7 +195,9 @@ namespace Newtonsoft.Json.Utilities // avoid error from expressions compiler because of abstract class if (type.IsAbstract()) + { return () => (T)Activator.CreateInstance(type); + } try { @@ -274,7 +282,9 @@ namespace Newtonsoft.Json.Utilities // use reflection for structs // expression doesn't correctly set value if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly) + { return LateBoundReflectionDelegateFactory.Instance.CreateSet(fieldInfo); + } ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source"); ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value"); @@ -308,7 +318,9 @@ namespace Newtonsoft.Json.Utilities // use reflection for structs // expression doesn't correctly set value if (propertyInfo.DeclaringType.IsValueType()) + { return LateBoundReflectionDelegateFactory.Instance.CreateSet(propertyInfo); + } Type instanceType = typeof(T); Type valueType = typeof(object); @@ -344,7 +356,9 @@ namespace Newtonsoft.Json.Utilities // check if a cast or conversion is required if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType))) + { return expression; + } return Expression.Convert(expression, targetType); } diff --git a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs index a2c76417..3573e258 100644 --- a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs @@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Utilities private static MethodCall CreateFSharpFuncCall(Type type, string methodName) { - MethodInfo innerMethodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic ); + MethodInfo innerMethodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance); MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); @@ -149,7 +149,7 @@ namespace Newtonsoft.Json.Utilities public static ObjectConstructor CreateMap(Type keyType, Type valueType) { - MethodInfo creatorDefinition = typeof (FSharpUtils).GetMethod("BuildMapCreator"); + MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator"); MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType); @@ -175,4 +175,5 @@ namespace Newtonsoft.Json.Utilities } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs b/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs index 349c0909..9173659f 100644 --- a/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs +++ b/Src/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs @@ -36,9 +36,13 @@ namespace Newtonsoft.Json.Utilities { generator.Emit(OpCodes.Ldarg_0); if (type.IsValueType()) + { generator.Emit(OpCodes.Unbox, type); + } else + { generator.Emit(OpCodes.Castclass, type); + } } public static void PushArrayInstance(this ILGenerator generator, int argsIndex, int arrayIndex) @@ -51,25 +55,37 @@ namespace Newtonsoft.Json.Utilities public static void BoxIfNeeded(this ILGenerator generator, Type type) { if (type.IsValueType()) + { generator.Emit(OpCodes.Box, type); + } else + { generator.Emit(OpCodes.Castclass, type); + } } public static void UnboxIfNeeded(this ILGenerator generator, Type type) { if (type.IsValueType()) + { generator.Emit(OpCodes.Unbox_Any, type); + } else + { generator.Emit(OpCodes.Castclass, type); + } } public static void CallMethod(this ILGenerator generator, MethodInfo methodInfo) { if (methodInfo.IsFinal || !methodInfo.IsVirtual) + { generator.Emit(OpCodes.Call, methodInfo); + } else + { generator.Emit(OpCodes.Callvirt, methodInfo); + } } public static void Return(this ILGenerator generator) @@ -78,4 +94,5 @@ namespace Newtonsoft.Json.Utilities } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs index f1c0e81b..46faa850 100644 --- a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs @@ -145,8 +145,8 @@ namespace Newtonsoft.Json.Utilities if (definition != null) { Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); - Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); - + Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + if (createdTypeDefinition != null && builderTypeDefinition != null) { MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => @@ -172,4 +172,5 @@ namespace Newtonsoft.Json.Utilities } } } + #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs index 9aaacb2a..ecca8141 100644 --- a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs @@ -118,10 +118,14 @@ namespace Newtonsoft.Json.Utilities public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) + { return HtmlCharEscapeFlags; + } if (quoteChar == '"') + { return DoubleQuoteCharEscapeFlags; + } return SingleQuoteCharEscapeFlags; } @@ -129,12 +133,16 @@ namespace Newtonsoft.Json.Utilities public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) + { return false; + } foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) + { return true; + } } return false; @@ -145,7 +153,9 @@ namespace Newtonsoft.Json.Utilities { // leading delimiter if (appendDelimiters) + { writer.Write(delimiter); + } if (s != null) { @@ -156,7 +166,9 @@ namespace Newtonsoft.Json.Utilities var c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) + { continue; + } string escapedValue; @@ -221,7 +233,9 @@ namespace Newtonsoft.Json.Utilities } if (escapedValue == null) + { continue; + } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); @@ -254,9 +268,13 @@ namespace Newtonsoft.Json.Utilities lastWritePosition = i + 1; if (!isEscapedUnicodeText) + { writer.Write(escapedValue); + } else + { writer.Write(writeBuffer, 0, UnicodeTextLength); + } } if (lastWritePosition == 0) @@ -269,7 +287,9 @@ namespace Newtonsoft.Json.Utilities int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) + { writeBuffer = new char[length]; + } s.CopyTo(lastWritePosition, writeBuffer, 0, length); @@ -280,7 +300,9 @@ namespace Newtonsoft.Json.Utilities // trailing delimiter if (appendDelimiters) + { writer.Write(delimiter); + } } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters) @@ -300,4 +322,4 @@ namespace Newtonsoft.Json.Utilities } } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index 4945a271..d5683925 100644 --- a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -67,7 +67,9 @@ namespace Newtonsoft.Json.Utilities ConstructorInfo c = method as ConstructorInfo; if (c != null) + { return (o, a) => c.Invoke(a); + } return (o, a) => method.Invoke(o, a); } @@ -77,7 +79,9 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(type, "type"); if (type.IsValueType()) + { return () => (T)Activator.CreateInstance(type); + } ConstructorInfo constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); diff --git a/Src/Newtonsoft.Json/Utilities/MathUtils.cs b/Src/Newtonsoft.Json/Utilities/MathUtils.cs index 753b4c2c..0110c431 100644 --- a/Src/Newtonsoft.Json/Utilities/MathUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MathUtils.cs @@ -35,29 +35,83 @@ namespace Newtonsoft.Json.Utilities { if (i < 10000000000) { - if (i < 10) return 1; - if (i < 100) return 2; - if (i < 1000) return 3; - if (i < 10000) return 4; - if (i < 100000) return 5; - if (i < 1000000) return 6; - if (i < 10000000) return 7; - if (i < 100000000) return 8; - if (i < 1000000000) return 9; + if (i < 10) + { + return 1; + } + if (i < 100) + { + return 2; + } + if (i < 1000) + { + return 3; + } + if (i < 10000) + { + return 4; + } + if (i < 100000) + { + return 5; + } + if (i < 1000000) + { + return 6; + } + if (i < 10000000) + { + return 7; + } + if (i < 100000000) + { + return 8; + } + if (i < 1000000000) + { + return 9; + } return 10; } else { - if (i < 100000000000) return 11; - if (i < 1000000000000) return 12; - if (i < 10000000000000) return 13; - if (i < 100000000000000) return 14; - if (i < 1000000000000000) return 15; - if (i < 10000000000000000) return 16; - if (i < 100000000000000000) return 17; - if (i < 1000000000000000000) return 18; - if (i < 10000000000000000000) return 19; + if (i < 100000000000) + { + return 11; + } + if (i < 1000000000000) + { + return 12; + } + if (i < 10000000000000) + { + return 13; + } + if (i < 100000000000000) + { + return 14; + } + if (i < 1000000000000000) + { + return 15; + } + if (i < 10000000000000000) + { + return 16; + } + if (i < 100000000000000000) + { + return 17; + } + if (i < 1000000000000000000) + { + return 18; + } + if (i < 10000000000000000000) + { + return 19; + } return 20; } @@ -66,7 +120,9 @@ namespace Newtonsoft.Json.Utilities public static char IntToHex(int n) { if (n <= 9) + { return (char)(n + 48); + } return (char)((n - 10) + 97); } @@ -74,9 +130,13 @@ namespace Newtonsoft.Json.Utilities public static int? Min(int? val1, int? val2) { if (val1 == null) + { return val2; + } if (val2 == null) + { return val1; + } return Math.Min(val1.Value, val2.Value); } @@ -84,9 +144,13 @@ namespace Newtonsoft.Json.Utilities public static int? Max(int? val1, int? val2) { if (val1 == null) + { return val2; + } if (val2 == null) + { return val1; + } return Math.Max(val1.Value, val2.Value); } @@ -94,9 +158,13 @@ namespace Newtonsoft.Json.Utilities public static double? Max(double? val1, double? val2) { if (val1 == null) + { return val2; + } if (val2 == null) + { return val1; + } return Math.Max(val1.Value, val2.Value); } @@ -106,7 +174,9 @@ namespace Newtonsoft.Json.Utilities const double epsilon = 2.2204460492503131E-16; if (d1 == d2) + { return true; + } double tolerance = ((Math.Abs(d1) + Math.Abs(d2)) + 10.0) * epsilon; double difference = d1 - d2; diff --git a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index 76f000b6..85b8d38e 100644 --- a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -40,22 +40,34 @@ namespace Newtonsoft.Json.Utilities public static bool ValueEquals(object objA, object objB) { if (objA == null && objB == null) + { return true; + } if (objA != null && objB == null) + { return false; + } if (objA == null && objB != null) + { return false; + } // comparing an Int32 and Int64 both of the same value returns false // make types the same then compare if (objA.GetType() != objB.GetType()) { if (ConvertUtils.IsInteger(objA) && ConvertUtils.IsInteger(objB)) + { return Convert.ToDecimal(objA, CultureInfo.CurrentCulture).Equals(Convert.ToDecimal(objB, CultureInfo.CurrentCulture)); + } else if ((objA is double || objA is float || objA is decimal) && (objB is double || objB is float || objB is decimal)) + { return MathUtils.ApproxEquals(Convert.ToDouble(objA, CultureInfo.CurrentCulture), Convert.ToDouble(objB, CultureInfo.CurrentCulture)); + } else + { return false; + } } return objA.Equals(objB); @@ -71,7 +83,9 @@ namespace Newtonsoft.Json.Utilities public static string ToString(object value) { if (value == null) + { return "{null}"; + } return (value is string) ? @"""" + value.ToString() + @"""" : value.ToString(); } @@ -80,13 +94,17 @@ namespace Newtonsoft.Json.Utilities { int lengthCompare = a1.Length.CompareTo(a2.Length); if (lengthCompare != 0) + { return lengthCompare; + } for (int i = 0; i < a1.Length; i++) { int valueCompare = a1[i].CompareTo(a2[i]); if (valueCompare != 0) + { return valueCompare; + } } return 0; @@ -129,10 +147,14 @@ namespace Newtonsoft.Json.Utilities internal static string FormatValueForPrint(object value) { if (value == null) + { return "{null}"; + } if (value is string) + { return @"""" + value + @""""; + } return value.ToString(); } diff --git a/Src/Newtonsoft.Json/Utilities/PropertyNameTable.cs b/Src/Newtonsoft.Json/Utilities/PropertyNameTable.cs index fd593a27..d017b602 100644 --- a/Src/Newtonsoft.Json/Utilities/PropertyNameTable.cs +++ b/Src/Newtonsoft.Json/Utilities/PropertyNameTable.cs @@ -49,7 +49,9 @@ namespace Newtonsoft.Json.Utilities public string Get(char[] key, int start, int length) { if (length == 0) + { return string.Empty; + } int hashCode = length + HashCodeRandomizer; hashCode += (hashCode << 7) ^ key[start]; @@ -64,7 +66,9 @@ namespace Newtonsoft.Json.Utilities for (Entry entry = _entries[hashCode & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == hashCode && TextEquals(entry.Value, key, start, length)) + { return entry.Value; + } } return null; @@ -73,11 +77,15 @@ namespace Newtonsoft.Json.Utilities public string Add(string key) { if (key == null) + { throw new ArgumentNullException("key"); + } int length = key.Length; if (length == 0) + { return string.Empty; + } int hashCode = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) @@ -90,13 +98,14 @@ namespace Newtonsoft.Json.Utilities for (Entry entry = _entries[hashCode & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == hashCode && entry.Value.Equals(key)) + { return entry.Value; + } } return AddEntry(key, hashCode); } - private string AddEntry(string str, int hashCode) { int index = hashCode & _mask; @@ -133,12 +142,16 @@ namespace Newtonsoft.Json.Utilities private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) + { return false; + } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) + { return false; + } } return true; } diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs index b2b19fe7..4b1838ca 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs @@ -40,11 +40,15 @@ namespace Newtonsoft.Json.Utilities { PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) + { return CreateGet(propertyInfo); + } FieldInfo fieldInfo = memberInfo as FieldInfo; if (fieldInfo != null) + { return CreateGet(fieldInfo); + } throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } @@ -53,11 +57,15 @@ namespace Newtonsoft.Json.Utilities { PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) + { return CreateSet(propertyInfo); + } FieldInfo fieldInfo = memberInfo as FieldInfo; if (fieldInfo != null) + { return CreateSet(fieldInfo); + } throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs b/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs index 9023f85a..7df9a012 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs @@ -33,6 +33,7 @@ using System.Globalization; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Utilities @@ -100,7 +101,9 @@ namespace Newtonsoft.Json.Utilities { MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public); if (members.Length != 1) + { throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } MemberInfo member = members.Single(); @@ -111,10 +114,14 @@ namespace Newtonsoft.Json.Utilities case MemberTypes.Field: case MemberTypes.Property: if (ReflectionUtils.CanReadMemberValue(member, false)) + { reflectionMember.Getter = delegateFactory.CreateGet(member); + } if (ReflectionUtils.CanSetMemberValue(member, false, false)) + { reflectionMember.Setter = delegateFactory.CreateSet(member); + } break; case MemberTypes.Method: MethodInfo method = (MethodInfo)member; @@ -138,10 +145,14 @@ namespace Newtonsoft.Json.Utilities } if (ReflectionUtils.CanReadMemberValue(member, false)) + { reflectionMember.Getter = delegateFactory.CreateGet(member); + } if (ReflectionUtils.CanSetMemberValue(member, false, false)) + { reflectionMember.Setter = delegateFactory.CreateSet(member); + } reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member); diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index 89ed5bd6..737dc39d 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -100,11 +100,15 @@ namespace Newtonsoft.Json.Utilities MethodInfo m = propertyInfo.GetGetMethod(); if (m != null && m.IsVirtual) + { return true; + } m = propertyInfo.GetSetMethod(); if (m != null && m.IsVirtual) + { return true; + } return false; } @@ -115,11 +119,15 @@ namespace Newtonsoft.Json.Utilities MethodInfo m = propertyInfo.GetGetMethod(); if (m != null) + { return m.GetBaseDefinition(); + } m = propertyInfo.GetSetMethod(); if (m != null) + { return m.GetBaseDefinition(); + } return null; } @@ -127,9 +135,13 @@ namespace Newtonsoft.Json.Utilities public static bool IsPublic(PropertyInfo property) { if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) + { return true; + } if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) + { return true; + } return false; } @@ -203,7 +215,9 @@ namespace Newtonsoft.Json.Utilities break; default: if (!skippingAssemblyDetails) + { builder.Append(current); + } break; } } @@ -216,7 +230,9 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) + { return true; + } return (GetDefaultConstructor(t, nonPublic) != null); } @@ -230,7 +246,9 @@ namespace Newtonsoft.Json.Utilities { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) + { bindingFlags = bindingFlags | BindingFlags.NonPublic; + } return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any()); } @@ -240,7 +258,9 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) + { return IsNullableType(t); + } return true; } @@ -262,7 +282,9 @@ namespace Newtonsoft.Json.Utilities public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition) { if (!type.IsGenericType()) + { return false; + } Type t = type.GetGenericTypeDefinition(); return (t == genericInterfaceDefinition); @@ -280,7 +302,9 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) + { throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); + } if (type.IsInterface()) { @@ -326,7 +350,9 @@ namespace Newtonsoft.Json.Utilities ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) + { throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); + } return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } @@ -370,7 +396,9 @@ namespace Newtonsoft.Json.Utilities if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition()) + { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); + } return genericListType.GetGenericArguments()[0]; } @@ -378,7 +406,7 @@ namespace Newtonsoft.Json.Utilities { return null; } - + throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } @@ -390,7 +418,9 @@ namespace Newtonsoft.Json.Utilities if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition()) + { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); + } Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); @@ -446,9 +476,13 @@ namespace Newtonsoft.Json.Utilities PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) + { return IsIndexedProperty(propertyInfo); + } else + { return false; + } } /// @@ -534,17 +568,25 @@ namespace Newtonsoft.Json.Utilities FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) + { return true; + } else if (fieldInfo.IsPublic) + { return true; + } return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanRead) + { return false; + } if (nonPublic) + { return true; + } return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; @@ -568,21 +610,33 @@ namespace Newtonsoft.Json.Utilities FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsLiteral) + { return false; + } if (fieldInfo.IsInitOnly && !canSetReadOnly) + { return false; + } if (nonPublic) + { return true; + } if (fieldInfo.IsPublic) + { return true; + } return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) + { return false; + } if (nonPublic) + { return true; + } return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; @@ -620,9 +674,13 @@ namespace Newtonsoft.Json.Utilities // if the hiding property is hiding a base property and it is virtual // then this ensures the derived property gets used if (resolvedMembers.Count == 0) + { resolvedMembers.Add(memberInfo); + } else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item") + { resolvedMembers.Add(memberInfo); + } } distinctMembers.AddRange(resolvedMembers); @@ -635,24 +693,36 @@ namespace Newtonsoft.Json.Utilities private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType() != MemberTypes.Property) + { return false; + } PropertyInfo propertyInfo = (PropertyInfo)memberInfo; if (!IsVirtual(propertyInfo)) + { return false; + } Type declaringType = propertyInfo.DeclaringType; if (!declaringType.IsGenericType()) + { return false; + } Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) + { return false; + } MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr); if (members.Length == 0) + { return false; + } Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) + { return false; + } return true; } @@ -676,7 +746,9 @@ namespace Newtonsoft.Json.Utilities T[] attributes = a as T[]; if (attributes != null) + { return attributes; + } return a.Cast().ToArray(); } @@ -697,7 +769,7 @@ namespace Newtonsoft.Json.Utilities Attribute[] attributes = a.Cast().ToArray(); #if (NET20 || NET35) - // ye olde .NET GetCustomAttributes doesn't respect the inherit argument + // ye olde .NET GetCustomAttributes doesn't respect the inherit argument if (inherit && t.BaseType != null) attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray(); #endif @@ -818,7 +890,9 @@ namespace Newtonsoft.Json.Utilities break; case ',': if (scope == 0) + { return i; + } break; } } @@ -960,7 +1034,9 @@ namespace Newtonsoft.Json.Utilities && p.DeclaringType == subTypeProperty.DeclaringType); if (index == -1) + { initialProperties.Add(subTypeProperty); + } } else { @@ -970,7 +1046,9 @@ namespace Newtonsoft.Json.Utilities && p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.GetBaseDefinition().DeclaringType)); if (index == -1) + { initialProperties.Add(subTypeProperty); + } } } } @@ -993,7 +1071,9 @@ namespace Newtonsoft.Json.Utilities public static object GetDefaultValue(Type type) { if (!type.IsValueType()) + { return null; + } switch (ConvertUtils.GetTypeCode(type)) { @@ -1031,7 +1111,9 @@ namespace Newtonsoft.Json.Utilities } if (IsNullable(type)) + { return null; + } // possibly use IL initobj for perf here? return Activator.CreateInstance(type); diff --git a/Src/Newtonsoft.Json/Utilities/StringUtils.cs b/Src/Newtonsoft.Json/Utilities/StringUtils.cs index 236dd23b..0e2f5961 100644 --- a/Src/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/StringUtils.cs @@ -84,15 +84,21 @@ namespace Newtonsoft.Json.Utilities public static bool IsWhiteSpace(string s) { if (s == null) + { throw new ArgumentNullException("s"); + } if (s.Length == 0) + { return false; + } for (int i = 0; i < s.Length; i++) { if (!char.IsWhiteSpace(s[i])) + { return false; + } } return true; @@ -119,9 +125,13 @@ namespace Newtonsoft.Json.Utilities public static int? GetLength(string value) { if (value == null) + { return null; + } else + { return value.Length; + } } public static void ToCharAsUnicode(char c, char[] buffer) @@ -137,9 +147,13 @@ namespace Newtonsoft.Json.Utilities public static TSource ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) { if (source == null) + { throw new ArgumentNullException("source"); + } if (valueSelector == null) + { throw new ArgumentNullException("valueSelector"); + } var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) @@ -157,10 +171,14 @@ namespace Newtonsoft.Json.Utilities public static string ToCamelCase(string s) { if (string.IsNullOrEmpty(s)) + { return s; + } if (!char.IsUpper(s[0])) + { return s; + } char[] chars = s.ToCharArray(); @@ -168,7 +186,9 @@ namespace Newtonsoft.Json.Utilities { bool hasNext = (i + 1 < chars.Length); if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) + { break; + } #if !(DOTNET || PORTABLE) chars[i] = char.ToLower(chars[i], CultureInfo.InvariantCulture); diff --git a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs index 7181ac5a..f956dec1 100644 --- a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs +++ b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs @@ -42,7 +42,9 @@ namespace Newtonsoft.Json.Utilities public ThreadSafeStore(Func creator) { if (creator == null) + { throw new ArgumentNullException("creator"); + } _creator = creator; _store = new Dictionary(); @@ -52,7 +54,9 @@ namespace Newtonsoft.Json.Utilities { TValue value; if (!_store.TryGetValue(key, out value)) + { return AddValue(key); + } return value; } @@ -73,7 +77,9 @@ namespace Newtonsoft.Json.Utilities // double check locking TValue checkValue; if (_store.TryGetValue(key, out checkValue)) + { return checkValue; + } Dictionary newStore = new Dictionary(_store); newStore[key] = value; diff --git a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs index 8f511546..16882702 100644 --- a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs +++ b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -30,6 +30,7 @@ using System.Reflection; using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; + #endif namespace Newtonsoft.Json.Utilities diff --git a/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs b/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs index c27874e7..9f122540 100644 --- a/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ValidationUtils.cs @@ -36,10 +36,14 @@ namespace Newtonsoft.Json.Utilities public static void ArgumentNotNullOrEmpty(string value, string parameterName) { if (value == null) + { throw new ArgumentNullException(parameterName); + } if (value.Length == 0) + { throw new ArgumentException("'{0}' cannot be empty.".FormatWith(CultureInfo.InvariantCulture, parameterName), parameterName); + } } public static void ArgumentTypeIsEnum(Type enumType, string parameterName) @@ -47,13 +51,17 @@ namespace Newtonsoft.Json.Utilities ArgumentNotNull(enumType, "enumType"); if (!enumType.IsEnum()) + { throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), parameterName); + } } public static void ArgumentNotNull(object value, string parameterName) { if (value == null) + { throw new ArgumentNullException(parameterName); + } } } } \ No newline at end of file diff --git a/Tools/NuGet/NuGet.exe b/Tools/NuGet/NuGet.exe index a9c681c8..9f8781de 100644 Binary files a/Tools/NuGet/NuGet.exe and b/Tools/NuGet/NuGet.exe differ