From a9e100e0a72ed6ee6ea90ec0b24d6021ff5fdfb8 Mon Sep 17 00:00:00 2001 From: JamesNK Date: Thu, 19 Jan 2012 05:48:24 +0000 Subject: [PATCH] -Added line number information to deserialization errors -Added BinaryReader/BinaryWriter constructor overloads to BsonReader/BsonWriter --- .../JsonTextReaderTest.cs | 18 +-- Src/Newtonsoft.Json.Tests/PerformanceTests.cs | 4 +- .../Properties/AssemblyInfo.cs | 2 +- .../Serialization/ConstructorHandlingTests.cs | 2 +- .../Serialization/DynamicTests.cs | 2 +- .../Serialization/JsonSerializerTest.cs | 34 ++--- .../MissingMemberHandlingTests.cs | 6 +- .../Serialization/PopulateTests.cs | 2 +- .../PreserveReferencesHandlingTests.cs | 4 +- .../SerializationErrorHandlingTests.cs | 2 +- .../Serialization/TypeNameHandlingTests.cs | 2 +- Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs | 24 ++-- Src/Newtonsoft.Json/Bson/BsonReader.cs | 58 +++++--- Src/Newtonsoft.Json/Bson/BsonWriter.cs | 18 ++- Src/Newtonsoft.Json/JsonReader.cs | 41 ++++++ Src/Newtonsoft.Json/JsonTextReader.cs | 81 +++++------ Src/Newtonsoft.Json/JsonWriter.cs | 8 +- .../Properties/AssemblyInfo.cs | 2 +- .../JsonSerializerInternalReader.cs | 126 ++++++++++-------- 19 files changed, 260 insertions(+), 176 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs index 9be99ab5..b07921f9 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs @@ -553,7 +553,7 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes: Line 1, position 3.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 3.")] public void ReadBytesNoStartWithUnexpectedEnd() { JsonReader reader = new JsonTextReader(new StringReader(@"[ ")); @@ -562,7 +562,7 @@ Parameter name: reader")] } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when parsing unquoted property name. Line 1, position 4.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing unquoted property name. Line 1, position 4.")] public void UnexpectedEndWhenParsingUnquotedProperty() { JsonReader reader = new JsonTextReader(new StringReader(@"{aww")); @@ -1086,7 +1086,7 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading decimal: Line 0, position 0.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading decimal. Line 0, position 0.")] public void ReadAsDecimalNoContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"")); @@ -1095,7 +1095,7 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes: Line 0, position 0.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes. Line 0, position 0.")] public void ReadAsBytesNoContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"")); @@ -1104,7 +1104,7 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes: Line 1, position 1.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 1.")] public void ReadAsBytesNoContentWrappedObject() { JsonTextReader reader = new JsonTextReader(new StringReader(@"{")); @@ -1114,7 +1114,7 @@ bye", reader.Value); #if !NET20 [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading date: Line 0, position 0.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading date. Line 0, position 0.")] public void ReadAsDateTimeOffsetNoContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"")); @@ -1164,7 +1164,7 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes: Line 1, position 2.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 2.")] public void ReadAsBytesIntegerArrayWithNoEnd() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[1")); @@ -1341,7 +1341,7 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing comment.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6.")] public void UnclosedComment() { JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf")); @@ -1598,7 +1598,7 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing constructor.")] + [ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing constructor. Line 1, position 7.")] public void ParseConstructorWithUnexpectedEnd() { string json = "new Dat"; diff --git a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs index 97af7d1c..11e0dc1d 100644 --- a/Src/Newtonsoft.Json.Tests/PerformanceTests.cs +++ b/Src/Newtonsoft.Json.Tests/PerformanceTests.cs @@ -36,8 +36,8 @@ namespace Newtonsoft.Json.Tests public class PerformanceTests : TestFixtureBase { - //private const int Iterations = 100; - private const int Iterations = 5000; + private const int Iterations = 100; + //private const int Iterations = 5000; private static SimpleObject CreateSimpleObject() { diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index ff6fcb59..7923661d 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -66,5 +66,5 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: [assembly: AssemblyVersion("4.0.5.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.0.5.14518")] +[assembly: AssemblyFileVersion("4.0.5.14519")] #endif diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs index 3f2a78e3..1f8ade66 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ConstructorHandlingTests.cs @@ -7,7 +7,7 @@ namespace Newtonsoft.Json.Tests.Serialization public class ConstructorHandlingTests : TestFixtureBase { [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.PrivateConstructorTestClass. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.PrivateConstructorTestClass. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 6.")] public void FailWithPrivateConstructorAndDefault() { string json = @"{Name:""Name!""}"; diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs index 501a3a87..b54690c2 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs @@ -185,7 +185,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type System.Dynamic.DynamicObject.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.")] public void NoPublicDefaultConstructor() { var settings = new JsonSerializerSettings(); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 7d5d7386..13b87831 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -1044,7 +1044,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null. Line 6, position 2.")] public void DeserializeRequiredMembersClassNullRequiredValueProperty() { string json = @"{ @@ -1074,7 +1074,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON. Line 3, position 2.")] public void RequiredMembersClassMissingRequiredProperty() { string json = @"{ @@ -1160,7 +1160,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14.")] public void DeserializeInterfaceProperty() { InterfacePropertyTestClass testClass = new InterfacePropertyTestClass(); @@ -1832,7 +1832,7 @@ keyword such as type of business."" #endif [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 15.")] public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments() { string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}"; @@ -1872,7 +1872,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array into type 'Newtonsoft.Json.Tests.TestObjects.Person'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array into type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")] public void CannotDeserializeArrayIntoObject() { string json = @"[]"; @@ -1881,7 +1881,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")] public void CannotDeserializeObjectIntoArray() { string json = @"{}"; @@ -1890,7 +1890,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")] public void CannotPopulateArrayIntoObject() { string json = @"[]"; @@ -1899,7 +1899,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")] public void CannotPopulateObjectIntoArray() { string json = @"{}"; @@ -1931,14 +1931,14 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Error converting value """" to type 'System.Int32'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value """" to type 'System.Int32'. Line 1, position 15.")] public void DeserializeEnsureTypeEmptyStringToIntError() { JsonConvert.DeserializeObject("{ReadTimeout:''}"); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17.")] public void DeserializeEnsureTypeNullToIntError() { JsonConvert.DeserializeObject("{ReadTimeout:null}"); @@ -2053,7 +2053,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Line 2, position 46.")] public void DeserializePersonKeyedDictionary() { string json = @@ -2318,7 +2318,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6.")] public void DeserializeDictionaryWithNoDefaultConstructor() { string json = "{key1:'value',key2:'value',key3:'value'}"; @@ -3267,7 +3267,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11.")] public void SerializeRefAdditionalContent() { //Additional text found in JSON string after finishing deserializing object. @@ -3281,12 +3281,12 @@ keyword such as type of business."" child.Add("Name", "Isabell"); child.Add("Father", reference); - var json = JsonConvert.SerializeObject(child); + var json = JsonConvert.SerializeObject(child, Formatting.Indented); JsonConvert.DeserializeObject>(json); } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string or null value.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string or null value. Line 5, position 14.")] public void SerializeRefBadType() { //Additional text found in JSON string after finishing deserializing object. @@ -3300,7 +3300,7 @@ keyword such as type of business."" child.Add("Name", "Isabell"); child.Add("Father", reference); - var json = JsonConvert.SerializeObject(child); + var json = JsonConvert.SerializeObject(child, Formatting.Indented); JsonConvert.DeserializeObject>(json); } @@ -4280,7 +4280,7 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.DateTime'.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4.")] public void DeserializeNullDateTimeValueTest() { JsonConvert.DeserializeObject("null", typeof (DateTime)); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs index 3e2b2fae..5cdcf339 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs @@ -34,7 +34,7 @@ namespace Newtonsoft.Json.Tests.Serialization public class MissingMemberHandlingTests : TestFixtureBase { [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11.")] public void MissingMemberDeserialize() { Product product = new Product(); @@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Tests.Serialization product.Price = 3.99M; product.Sizes = new string[] { "Small", "Medium", "Large" }; - string output = JsonConvert.SerializeObject(product); + string output = JsonConvert.SerializeObject(product, Formatting.Indented); //{ // "Name": "Apple", // "ExpiryDate": new Date(1230422400000), @@ -115,7 +115,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11.")] public void MissingMemeber() { string json = @"{""Missing"":1}"; diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs index c63445de..f00a40a4 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs @@ -134,7 +134,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unexpected initial token 'Integer' when populating object. Expected JSON object or array.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.")] public void PopulateWithBadJson() { JsonConvert.PopulateObject("1", new Person()); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs index cb72ffbd..40f52514 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs @@ -202,7 +202,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]. Line 3, position 15.")] public void DeserializeArraysWithPreserveObjectReferences() { string json = @"{ @@ -268,7 +268,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unexpected end when deserializing object.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unexpected end when deserializing object. Line 2, position 9.")] public void UnexpectedEnd() { string json = @"{ diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs index 70f14947..61e76d81 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs @@ -288,7 +288,7 @@ namespace Newtonsoft.Json.Tests.Serialization } Assert.AreEqual(1, errors.Count); - Assert.AreEqual(@"Error converting value ""kjhkjhkjhkjh"" to type 'System.DateTime'.", errors[0]); + Assert.AreEqual(@"Error converting value ""kjhkjhkjhkjh"" to type 'System.DateTime'. Line 1, position 16.", errors[0]); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs index 9c386960..e256e0d1 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs @@ -291,7 +291,7 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved.")] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Line 3, position 56.")] public void DeserializeTypeNameOnly() { string json = @"{ diff --git a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs index e51294c5..ff2f08c4 100644 --- a/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs @@ -18,10 +18,10 @@ namespace Newtonsoft.Json.Bson public DateTimeKind DateTimeKindHandling { get; set; } - public BsonBinaryWriter(Stream stream) + public BsonBinaryWriter(BinaryWriter writer) { DateTimeKindHandling = DateTimeKind.Utc; - _writer = new BinaryWriter(stream); + _writer = writer; } public void Flush() @@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Bson { case BsonType.Object: { - BsonObject value = (BsonObject) t; + BsonObject value = (BsonObject)t; _writer.Write(value.CalculatedSize); foreach (BsonProperty property in value) { @@ -59,7 +59,7 @@ namespace Newtonsoft.Json.Bson break; case BsonType.Array: { - BsonArray value = (BsonArray) t; + BsonArray value = (BsonArray)t; _writer.Write(value.CalculatedSize); int index = 0; foreach (BsonToken c in value) @@ -74,7 +74,7 @@ namespace Newtonsoft.Json.Bson break; case BsonType.Integer: { - BsonValue value = (BsonValue) t; + BsonValue value = (BsonValue)t; _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture)); } break; @@ -113,7 +113,7 @@ namespace Newtonsoft.Json.Bson if (value.Value is DateTime) { - DateTime dateTime = (DateTime) value.Value; + DateTime dateTime = (DateTime)value.Value; if (DateTimeKindHandling == DateTimeKind.Utc) dateTime = dateTime.ToUniversalTime(); else if (DateTimeKindHandling == DateTimeKind.Local) @@ -124,7 +124,7 @@ namespace Newtonsoft.Json.Bson #if !PocketPC && !NET20 else { - DateTimeOffset dateTimeOffset = (DateTimeOffset) value.Value; + DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value; ticks = JsonConvert.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset); } #endif @@ -152,7 +152,7 @@ namespace Newtonsoft.Json.Bson break; case BsonType.Regex: { - BsonRegex value = (BsonRegex) t; + BsonRegex value = (BsonRegex)t; WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null); WriteString((string)value.Options.Value, value.Options.ByteCount, null); @@ -214,7 +214,7 @@ namespace Newtonsoft.Json.Bson { case BsonType.Object: { - BsonObject value = (BsonObject) t; + BsonObject value = (BsonObject)t; int bases = 4; foreach (BsonProperty p in value) @@ -256,7 +256,7 @@ namespace Newtonsoft.Json.Bson case BsonType.String: { BsonString value = (BsonString)t; - string s = (string) value.Value; + string s = (string)value.Value; value.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0; value.CalculatedSize = CalculateSizeWithLength(value.ByteCount, value.IncludeLength); @@ -271,7 +271,7 @@ namespace Newtonsoft.Json.Bson return 8; case BsonType.Binary: { - BsonValue value = (BsonValue) t; + BsonValue value = (BsonValue)t; byte[] data = (byte[])value.Value; value.CalculatedSize = 4 + 1 + data.Length; @@ -282,7 +282,7 @@ namespace Newtonsoft.Json.Bson return 12; case BsonType.Regex: { - BsonRegex value = (BsonRegex) t; + BsonRegex value = (BsonRegex)t; int size = 0; size += CalculateSize(value.Pattern); size += CalculateSize(value.Options); diff --git a/Src/Newtonsoft.Json/Bson/BsonReader.cs b/Src/Newtonsoft.Json/Bson/BsonReader.cs index 569183f1..092d6ca8 100644 --- a/Src/Newtonsoft.Json/Bson/BsonReader.cs +++ b/Src/Newtonsoft.Json/Bson/BsonReader.cs @@ -39,10 +39,10 @@ namespace Newtonsoft.Json.Bson public class BsonReader : JsonReader { private const int MaxCharBytesSize = 128; - private static readonly byte[] SeqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence - private static readonly byte[] SeqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence - private static readonly byte[] SeqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence - private static readonly byte[] SeqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence + private static readonly byte[] SeqRange1 = new byte[] {0, 127}; // range of 1-byte sequence + private static readonly byte[] SeqRange2 = new byte[] {194, 223}; // range of 2-byte sequence + private static readonly byte[] SeqRange3 = new byte[] {224, 239}; // range of 3-byte sequence + private static readonly byte[] SeqRange4 = new byte[] {240, 244}; // range of 4-byte sequence private readonly BinaryReader _reader; private readonly List _stack; @@ -126,6 +126,15 @@ namespace Newtonsoft.Json.Bson { } + /// + /// Initializes a new instance of the class. + /// + /// The reader. + public BsonReader(BinaryReader reader) + : this(reader, false, DateTimeKind.Local) + { + } + /// /// Initializes a new instance of the class. /// @@ -141,6 +150,21 @@ namespace Newtonsoft.Json.Bson _dateTimeKindHandling = dateTimeKindHandling; } + /// + /// Initializes a new instance of the class. + /// + /// The reader. + /// if set to true the root object will be read as a JSON array. + /// The used when reading values from BSON. + public BsonReader(BinaryReader reader, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling) + { + ValidationUtils.ArgumentNotNull(reader, "reader"); + _reader = reader; + _stack = new List(); + _readRootValueAsArray = readRootValueAsArray; + _dateTimeKindHandling = dateTimeKindHandling; + } + private string ReadElement() { _currentElementType = ReadType(); @@ -169,7 +193,7 @@ namespace Newtonsoft.Json.Bson if (TokenType == JsonToken.Null) return null; if (TokenType == JsonToken.Bytes) - return (byte[])Value; + return (byte[]) Value; if (ReaderIsSerializerInArray()) return null; @@ -214,7 +238,7 @@ namespace Newtonsoft.Json.Bson if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float) { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture)); - return (decimal)Value; + return (decimal) Value; } if (ReaderIsSerializerInArray()) @@ -238,8 +262,8 @@ namespace Newtonsoft.Json.Bson return null; if (TokenType == JsonToken.Date) { - SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value)); - return (DateTimeOffset)Value; + SetToken(JsonToken.Date, new DateTimeOffset((DateTime) Value)); + return (DateTimeOffset) Value; } if (ReaderIsSerializerInArray()) @@ -576,7 +600,7 @@ namespace Newtonsoft.Json.Bson _bsonReaderState = BsonReaderState.CodeWScopeStart; break; case BsonType.Integer: - SetToken(JsonToken.Integer, (long)ReadInt32()); + SetToken(JsonToken.Integer, (long) ReadInt32()); break; case BsonType.TimeStamp: case BsonType.Long: @@ -591,7 +615,7 @@ namespace Newtonsoft.Json.Bson { int dataLength = ReadInt32(); - BsonBinaryType binaryType = (BsonBinaryType)ReadByte(); + BsonBinaryType binaryType = (BsonBinaryType) ReadByte(); #pragma warning disable 612,618 // the old binary type has the data length repeated in the data for some reason @@ -641,7 +665,7 @@ namespace Newtonsoft.Json.Bson int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0); if (builder == null) - builder = new StringBuilder(MaxCharBytesSize * 2); + builder = new StringBuilder(MaxCharBytesSize*2); builder.Append(_charBuffer, 0, charCount); @@ -663,8 +687,7 @@ namespace Newtonsoft.Json.Bson offset = 0; } } - } - while (true); + } while (true); } private string ReadLengthString() @@ -695,8 +718,8 @@ namespace Newtonsoft.Json.Bson do { int count = ((length - totalBytesRead) > MaxCharBytesSize - offset) - ? MaxCharBytesSize - offset - : length - totalBytesRead; + ? MaxCharBytesSize - offset + : length - totalBytesRead; int byteCount = _reader.BaseStream.Read(_byteBuffer, offset, count); @@ -737,8 +760,7 @@ namespace Newtonsoft.Json.Bson offset = 0; } } - } - while (totalBytesRead < length); + } while (totalBytesRead < length); return builder.ToString(); } @@ -819,7 +841,7 @@ namespace Newtonsoft.Json.Bson private BsonType ReadType() { MovePosition(1); - return (BsonType)_reader.ReadSByte(); + return (BsonType) _reader.ReadSByte(); } private void MovePosition(int count) diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index 1502ad8b..09c5283c 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -63,7 +63,17 @@ namespace Newtonsoft.Json.Bson public BsonWriter(Stream stream) { ValidationUtils.ArgumentNotNull(stream, "stream"); - _writer = new BsonBinaryWriter(stream); + _writer = new BsonBinaryWriter(new BinaryWriter(stream)); + } + + /// + /// Initializes a new instance of the class. + /// + /// The writer. + public BsonWriter(BinaryWriter writer) + { + ValidationUtils.ArgumentNotNull(writer, "writer"); + _writer = new BsonBinaryWriter(writer); } /// @@ -189,12 +199,12 @@ namespace Newtonsoft.Json.Bson { if (_parent is BsonObject) { - ((BsonObject)_parent).Add(_propertyName, token); + ((BsonObject) _parent).Add(_propertyName, token); _propertyName = null; } else { - ((BsonArray)_parent).Add(token); + ((BsonArray) _parent).Add(token); } } else @@ -208,6 +218,7 @@ namespace Newtonsoft.Json.Bson } #region WriteValue methods + /// /// Writes a null value. /// @@ -440,6 +451,7 @@ namespace Newtonsoft.Json.Bson base.WriteValue(value); AddToken(new BsonString(value.ToString(), true)); } + #endregion /// diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index c2cd3089..0e919e7c 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -450,5 +450,46 @@ namespace Newtonsoft.Json _token = JsonToken.None; _value = null; } + + internal JsonReaderException CreateReaderException(JsonReader reader, string message) + { + return CreateReaderException(reader, message, null); + } + + internal JsonReaderException CreateReaderException(JsonReader reader, string message, Exception ex) + { + return CreateReaderException(reader as IJsonLineInfo, message, ex); + } + + internal JsonReaderException CreateReaderException(IJsonLineInfo lineInfo, string message, Exception ex) + { + message = FormatExceptionMessage(lineInfo, message); + + int lineNumber; + int linePosition; + if (lineInfo != null) + { + lineNumber = lineInfo.LineNumber; + linePosition = lineInfo.LinePosition; + } + else + { + lineNumber = 0; + linePosition = 0; + } + + return new JsonReaderException(message, ex, lineNumber, linePosition); + } + + internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string message) + { + if (!message.EndsWith(".")) + message += "."; + + if (lineInfo != null) + message += " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); + + return message; + } } } diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index 1963c8e4..6455bd02 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -260,12 +260,6 @@ namespace Newtonsoft.Json return true; } - private JsonReaderException CreateJsonReaderException(string format, params object[] args) - { - string message = format.FormatWith(CultureInfo.InvariantCulture, args); - return new JsonReaderException(message, null, LineNumber, LinePosition); - } - private static TimeSpan ReadOffset(string offsetText) { bool negative = (offsetText[0] == '-'); @@ -351,11 +345,8 @@ namespace Newtonsoft.Json if (TokenType == JsonToken.StartObject) { - int startObjectLineNumber = LineNumber; - int startObjectLinePosition = LinePosition; - if (!ReadInternal()) - throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end when reading bytes."); if (Value.ToString() == "$type") { @@ -370,7 +361,7 @@ namespace Newtonsoft.Json } } - throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", JsonToken.StartObject, startObjectLineNumber, startObjectLinePosition); + throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } return false; @@ -389,7 +380,7 @@ namespace Newtonsoft.Json do { if (!ReadInternal()) - throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end when reading bytes."); } while (TokenType == JsonToken.Comment); if (IsWrappedInTypeObject()) @@ -423,17 +414,17 @@ namespace Newtonsoft.Json // skip break; default: - throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } - throw CreateJsonReaderException("Unexpected end when reading bytes: Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end when reading bytes."); } if (ReaderIsSerializerInArray()) return null; - throw CreateJsonReaderException("Unexpected token when reading bytes: {0}. Line {1}, position {2}.", TokenType, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } /// @@ -447,7 +438,7 @@ namespace Newtonsoft.Json do { if (!ReadInternal()) - throw CreateJsonReaderException("Unexpected end when reading decimal: Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end when reading decimal."); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) @@ -465,7 +456,7 @@ namespace Newtonsoft.Json if (ReaderIsSerializerInArray()) return null; - throw CreateJsonReaderException("Unexpected token when reading decimal: {0}. Line {1}, position {2}.", TokenType, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected token when reading decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } #if !NET20 @@ -480,7 +471,7 @@ namespace Newtonsoft.Json do { if (!ReadInternal()) - throw CreateJsonReaderException("Unexpected end when reading date: Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end when reading date."); } while (TokenType == JsonToken.Comment); if (TokenType == JsonToken.Null) @@ -498,7 +489,7 @@ namespace Newtonsoft.Json if (ReaderIsSerializerInArray()) return null; - throw CreateJsonReaderException("Unexpected token when reading date: {0}. Line {1}, position {2}.", TokenType, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected token when reading date: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } #endif @@ -541,7 +532,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Additional text encountered after finished reading JSON content: {0}. Line {1}, position {2}.", _chars[_charPos], LineNumber, LinePosition); + throw CreateReaderException(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } } return false; @@ -550,7 +541,7 @@ namespace Newtonsoft.Json case State.Error: break; default: - throw CreateJsonReaderException("Unexpected state: {0}. Line {1}, position {2}.", CurrentState, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } } @@ -574,7 +565,7 @@ namespace Newtonsoft.Json if (ReadData(true) == 0) { _charPos = charPos; - throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, LineNumber, LinePosition); + throw CreateReaderException(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } } break; @@ -583,7 +574,7 @@ namespace Newtonsoft.Json if (!EnsureChars(0, true)) { _charPos = charPos; - throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, LineNumber, LinePosition); + throw CreateReaderException(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } // start of escape sequence @@ -639,13 +630,13 @@ namespace Newtonsoft.Json else { _charPos = charPos; - throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end while parsing unicode character."); } break; default: charPos++; _charPos = charPos; - throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", @"\" + currentChar, LineNumber, LinePosition); + throw CreateReaderException(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); } if (buffer == null) @@ -822,7 +813,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("After parsing a value an unexpected character was encountered: {0}. Line {1}, position {2}.", currentChar, LineNumber, LinePosition); + throw CreateReaderException(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } break; } @@ -901,7 +892,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Invalid property identifier character: {0}. Line {1}, position {2}.", _chars[_charPos], LineNumber, LinePosition); + throw CreateReaderException(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } string propertyName = _stringReference.ToString(); @@ -909,7 +900,7 @@ namespace Newtonsoft.Json EatWhitespace(false); if (_chars[_charPos] != ':') - throw CreateJsonReaderException("Invalid character after parsing property name. Expected ':' but got: {0}. Line {1}, position {2}.", _chars[_charPos], LineNumber, LinePosition); + throw CreateReaderException(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; @@ -938,7 +929,7 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) - throw CreateJsonReaderException("Unexpected end when parsing unquoted property name. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end while parsing unquoted property name."); break; } @@ -959,7 +950,7 @@ namespace Newtonsoft.Json return; } - throw CreateJsonReaderException("Invalid JavaScript property identifier character: {0}. Line {1}, position {2}.", currentChar, LineNumber, LinePosition); + throw CreateReaderException(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } @@ -1003,11 +994,11 @@ namespace Newtonsoft.Json else if (next == 'e') ParseConstructor(); else - throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", _chars[_charPos], LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } else { - throw CreateJsonReaderException("Unexpected end. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected end."); } return true; case 'N': @@ -1074,7 +1065,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Unexpected character encountered while parsing value: {0}. Line {1}, position {2}.", currentChar, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } @@ -1157,7 +1148,7 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) - throw CreateJsonReaderException("Unexpected end while parsing constructor."); + throw CreateReaderException(this, "Unexpected end while parsing constructor."); } else { @@ -1195,7 +1186,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Unexpected character while parsing constructor: {0}. Line {1}, position {2}.", currentChar, LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } @@ -1205,7 +1196,7 @@ namespace Newtonsoft.Json EatWhitespace(false); if (_chars[_charPos] != '(') - throw CreateJsonReaderException("Unexpected character while parsing constructor: {0}. Line {1}, position {2}.", _chars[_charPos], LineNumber, LinePosition); + throw CreateReaderException(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; @@ -1313,7 +1304,7 @@ namespace Newtonsoft.Json _charPos++; if (!EnsureChars(1, false) || _chars[_charPos] != '*') - throw CreateJsonReaderException("Error parsing comment. Expected: *, got {0}. Line {1}, position {2}.", _chars[_charPos], LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); else _charPos++; @@ -1329,7 +1320,7 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) - throw CreateJsonReaderException("Unexpected end while parsing comment."); + throw CreateReaderException(this, "Unexpected end while parsing comment."); } else { @@ -1442,7 +1433,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing boolean value."); } } @@ -1454,7 +1445,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing null value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing null value."); } } @@ -1466,7 +1457,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing undefined value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing undefined value."); } } @@ -1478,7 +1469,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing boolean value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing boolean value."); } } @@ -1490,7 +1481,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing negative infinity value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing negative infinity value."); } } @@ -1502,7 +1493,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing positive infinity value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing positive infinity value."); } } @@ -1514,7 +1505,7 @@ namespace Newtonsoft.Json } else { - throw CreateJsonReaderException("Error parsing NaN value. Line {0}, position {1}.", LineNumber, LinePosition); + throw CreateReaderException(this, "Error parsing NaN value."); } } diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index fb430bf1..aa77b0ff 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -441,17 +441,17 @@ namespace Newtonsoft.Json private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) - throw new Exception("Unexpected end while reading date constructor."); + throw new Exception("Unexpected end when reading date constructor."); if (reader.TokenType != JsonToken.Integer) - throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType); + throw new Exception("Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType); long ticks = (long)reader.Value; DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) - throw new Exception("Unexpected end while reading date constructor."); + throw new Exception("Unexpected end when reading date constructor."); if (reader.TokenType != JsonToken.EndConstructor) - throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType); + throw new Exception("Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType); WriteValue(date); } diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index 2a2a8264..f65a5c9a 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -85,7 +85,7 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.0.5.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.0.5.14518")] +[assembly: AssemblyFileVersion("4.0.5.14519")] #endif [assembly: CLSCompliant(true)] diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index bb77dda7..cc1953b2 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -67,7 +67,7 @@ namespace Newtonsoft.Json.Serialization if (contract is JsonArrayContract) PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, (JsonArrayContract) contract); else - throw new JsonSerializationException("Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } else if (reader.TokenType == JsonToken.StartObject) { @@ -86,11 +86,11 @@ namespace Newtonsoft.Json.Serialization else if (contract is JsonObjectContract) PopulateObject(target, reader, (JsonObjectContract) contract, id); else - throw new JsonSerializationException("Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } else { - throw new JsonSerializationException("Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw CreateSerializationException(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } @@ -241,7 +241,7 @@ namespace Newtonsoft.Json.Serialization case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: - return EnsureType(reader.Value, CultureInfo.InvariantCulture, contract, objectType); + return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.String: // convert empty string to null automatically for nullable types if (string.IsNullOrEmpty((string) reader.Value) && objectType != typeof(string) && contract.IsNullable) @@ -251,7 +251,7 @@ namespace Newtonsoft.Json.Serialization if (objectType == typeof (byte[])) return Convert.FromBase64String((string) reader.Value); - return EnsureType(reader.Value, CultureInfo.InvariantCulture, contract, objectType); + return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.StartConstructor: case JsonToken.EndConstructor: string constructorName = reader.Value.ToString(); @@ -262,18 +262,35 @@ namespace Newtonsoft.Json.Serialization if (objectType == typeof (DBNull)) return DBNull.Value; - return EnsureType(reader.Value, CultureInfo.InvariantCulture, contract, objectType); + return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Raw: return new JRaw((string) reader.Value); case JsonToken.Comment: // ignore break; default: - throw new JsonSerializationException("Unexpected token while deserializing object: " + reader.TokenType); + throw CreateSerializationException(reader, "Unexpected token while deserializing object: " + reader.TokenType); } } while (reader.Read()); - throw new JsonSerializationException("Unexpected end when deserializing object."); + throw CreateSerializationException(reader, "Unexpected end when deserializing object."); + } + + private JsonSerializationException CreateSerializationException(JsonReader reader, string message) + { + return CreateSerializationException(reader, message, null); + } + + private JsonSerializationException CreateSerializationException(JsonReader reader, string message, Exception ex) + { + return CreateSerializationException(reader as IJsonLineInfo, message, ex); + } + + private JsonSerializationException CreateSerializationException(IJsonLineInfo lineInfo, string message, Exception ex) + { + message = JsonReader.FormatExceptionMessage(lineInfo, message); + + return new JsonSerializationException(message, ex); } private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter) @@ -324,7 +341,7 @@ namespace Newtonsoft.Json.Serialization { CheckedRead(reader); if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null) - throw new JsonSerializationException("JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + throw CreateSerializationException(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); string reference = (reader.Value != null) ? reader.Value.ToString() : null; @@ -333,7 +350,7 @@ namespace Newtonsoft.Json.Serialization if (reference != null) { if (reader.TokenType == JsonToken.PropertyName) - throw new JsonSerializationException("Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + throw CreateSerializationException(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); return Serializer.ReferenceResolver.ResolveReference(this, reference); } @@ -347,8 +364,6 @@ namespace Newtonsoft.Json.Serialization CheckedRead(reader); string qualifiedTypeName = reader.Value.ToString(); - CheckedRead(reader); - if ((((member != null) ? member.TypeNameHandling : null) ?? Serializer.TypeNameHandling) != TypeNameHandling.None) { string typeName; @@ -362,18 +377,21 @@ namespace Newtonsoft.Json.Serialization } catch (Exception ex) { - throw new JsonSerializationException("Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); + throw CreateSerializationException(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); } if (specifiedType == null) - throw new JsonSerializationException("Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); + throw CreateSerializationException(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); if (objectType != null && !objectType.IsAssignableFrom(specifiedType)) - throw new JsonSerializationException("Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); + throw CreateSerializationException(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); objectType = specifiedType; contract = GetContractSafe(specifiedType); } + + CheckedRead(reader); + specialProperty = true; } else if (string.Equals(propertyName, JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) @@ -405,7 +423,7 @@ namespace Newtonsoft.Json.Serialization return CreateJObject(reader); if (contract == null) - throw new JsonSerializationException("Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); JsonDictionaryContract dictionaryContract = contract as JsonDictionaryContract; if (dictionaryContract != null) @@ -455,17 +473,17 @@ namespace Newtonsoft.Json.Serialization } #endif - throw new JsonSerializationException("Cannot deserialize JSON object into type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "Cannot deserialize JSON object into type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } - private JsonArrayContract EnsureArrayContract(Type objectType, JsonContract contract) + private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) { if (contract == null) - throw new JsonSerializationException("Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); JsonArrayContract arrayContract = contract as JsonArrayContract; if (arrayContract == null) - throw new JsonSerializationException("Cannot deserialize JSON array into type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "Cannot deserialize JSON array into type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); return arrayContract; } @@ -473,7 +491,7 @@ namespace Newtonsoft.Json.Serialization private void CheckedRead(JsonReader reader) { if (!reader.Read()) - throw new JsonSerializationException("Unexpected end when deserializing object."); + throw CreateSerializationException(reader, "Unexpected end when deserializing object."); } private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string reference) @@ -481,7 +499,7 @@ namespace Newtonsoft.Json.Serialization object value; if (HasDefinedType(objectType)) { - JsonArrayContract arrayContract = EnsureArrayContract(objectType, contract); + JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract); if (existingValue == null) value = CreateAndPopulateList(reader, reference, arrayContract); @@ -504,7 +522,7 @@ namespace Newtonsoft.Json.Serialization ); } - private object EnsureType(object value, CultureInfo culture, JsonContract contract, Type targetType) + private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType) { if (targetType == null) return value; @@ -537,7 +555,7 @@ namespace Newtonsoft.Json.Serialization } catch (Exception ex) { - throw new JsonSerializationException("Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex); + throw CreateSerializationException(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex); } } @@ -649,7 +667,7 @@ namespace Newtonsoft.Json.Serialization (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) dictionary = contract.DefaultCreator(); else - throw new JsonSerializationException("Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); IWrappedDictionary dictionaryWrapper = contract.CreateWrapper(dictionary); @@ -680,11 +698,11 @@ namespace Newtonsoft.Json.Serialization try { - keyValue = EnsureType(keyValue, CultureInfo.InvariantCulture, contract.DictionaryKeyContract, contract.DictionaryKeyType); + keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.DictionaryKeyContract, contract.DictionaryKeyType); } catch (Exception ex) { - throw new JsonSerializationException("Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex); + throw CreateSerializationException(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex); } if (contract.DictionaryValueContract == null) @@ -693,7 +711,7 @@ namespace Newtonsoft.Json.Serialization JsonConverter dictionaryValueConverter = GetConverter(contract.DictionaryValueContract, null); if (!ReadForType(reader, contract.DictionaryValueContract, dictionaryValueConverter != null, false)) - throw new JsonSerializationException("Unexpected end when deserializing object."); + throw CreateSerializationException(reader, "Unexpected end when deserializing object."); dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, contract.DictionaryValueContract, dictionaryValueConverter); } @@ -712,11 +730,11 @@ namespace Newtonsoft.Json.Serialization return dictionary.UnderlyingDictionary; default: - throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); + throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (reader.Read()); - throw new JsonSerializationException("Unexpected end when deserializing object."); + throw CreateSerializationException(reader, "Unexpected end when deserializing object."); } private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract) @@ -724,14 +742,14 @@ namespace Newtonsoft.Json.Serialization return CollectionUtils.CreateAndPopulateList(contract.CreatedType, (l, isTemporaryListReference) => { if (reference != null && isTemporaryListReference) - throw new JsonSerializationException("Cannot preserve reference to array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); #if !PocketPC if (contract.OnSerializing != null && isTemporaryListReference) - throw new JsonSerializationException("Cannot call OnSerializing on an array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); #endif if (contract.OnError != null && isTemporaryListReference) - throw new JsonSerializationException("Cannot call OnError on an array or readonly list: {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); PopulateList(contract.CreateWrapper(l), reader, reference, contract); }); @@ -790,7 +808,7 @@ namespace Newtonsoft.Json.Serialization } } - throw new JsonSerializationException("Unexpected end when deserializing array."); + throw CreateSerializationException(reader, "Unexpected end when deserializing array."); } #if !SILVERLIGHT && !PocketPC @@ -808,7 +826,7 @@ namespace Newtonsoft.Json.Serialization case JsonToken.PropertyName: string memberName = reader.Value.ToString(); if (!reader.Read()) - throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); serializationInfo.AddValue(memberName, JToken.ReadFrom(reader)); break; @@ -818,12 +836,12 @@ namespace Newtonsoft.Json.Serialization exit = true; break; default: - throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); + throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); if (contract.ISerializableCreator == null) - throw new JsonSerializationException("ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw CreateSerializationException(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType)); object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context); @@ -844,13 +862,13 @@ namespace Newtonsoft.Json.Serialization IDynamicMetaObjectProvider newObject = null; if (contract.UnderlyingType.IsInterface || contract.UnderlyingType.IsAbstract) - throw new JsonSerializationException("Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator(); else - throw new JsonSerializationException("Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (id != null) Serializer.ReferenceResolver.AddReference(this, id, newObject); @@ -870,7 +888,7 @@ namespace Newtonsoft.Json.Serialization try { if (!reader.Read()) - throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw CreateSerializationException(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); @@ -908,7 +926,7 @@ namespace Newtonsoft.Json.Serialization exit = true; break; default: - throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); + throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); @@ -923,7 +941,7 @@ namespace Newtonsoft.Json.Serialization object newObject = null; if (contract.UnderlyingType.IsInterface || contract.UnderlyingType.IsAbstract) - throw new JsonSerializationException("Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw CreateSerializationException(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (contract.OverrideConstructor != null) { @@ -943,7 +961,7 @@ namespace Newtonsoft.Json.Serialization } if (newObject == null) - throw new JsonSerializationException("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, contract.UnderlyingType)); + throw CreateSerializationException(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, contract.UnderlyingType)); PopulateObject(newObject, reader, contract, id); return newObject; @@ -1054,7 +1072,7 @@ namespace Newtonsoft.Json.Serialization JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter); if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false)) - throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (!property.Ignored) propertyValues[property] = CreateValueProperty(reader, property, propertyConverter, null, true, null); @@ -1064,10 +1082,10 @@ namespace Newtonsoft.Json.Serialization else { if (!reader.Read()) - throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) - throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); + throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); reader.Skip(); } @@ -1078,7 +1096,7 @@ namespace Newtonsoft.Json.Serialization exit = true; break; default: - throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); + throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); @@ -1163,7 +1181,7 @@ namespace Newtonsoft.Json.Serialization if (property == null) { if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) - throw new JsonSerializationException("Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); + throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); reader.Skip(); continue; @@ -1175,7 +1193,7 @@ namespace Newtonsoft.Json.Serialization JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter); if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false)) - throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); SetPropertyPresence(reader, property, propertiesPresence); @@ -1199,18 +1217,18 @@ namespace Newtonsoft.Json.Serialization { case PropertyPresence.None: if (property.Required == Required.AllowNull || property.Required == Required.Always) - throw new JsonSerializationException("Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + throw CreateSerializationException(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); 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(property.DefaultValue, CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); + property.ValueProvider.SetValue(newObject, EnsureType(reader, property.DefaultValue, CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); break; case PropertyPresence.Null: if (property.Required == Required.Always) - throw new JsonSerializationException("Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + throw CreateSerializationException(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); break; } } @@ -1221,11 +1239,11 @@ namespace Newtonsoft.Json.Serialization // ignore break; default: - throw new JsonSerializationException("Unexpected token when deserializing object: " + reader.TokenType); + throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (reader.Read()); - throw new JsonSerializationException("Unexpected end when deserializing object."); + throw CreateSerializationException(reader, "Unexpected end when deserializing object."); } private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary requiredProperties)