-Added Path to JsonReaderException/JsonSerializationException messages

-Added JsonException
-Fixed all Exceptions thrown to be more specific
This commit is contained in:
James Newton-King
2012-04-21 17:25:44 +12:00
parent c120bf530d
commit a7bddf989f
69 changed files with 1400 additions and 1161 deletions
@@ -275,7 +275,8 @@ namespace Newtonsoft.Json.Tests.Bson
[Test] [Test]
public void ReadAsInt32BadString() public void ReadAsInt32BadString()
{ {
ExceptionAssert.Throws<JsonReaderException>("Could not convert string to integer: a.", ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to integer: a. Path '[0]'.",
() => () =>
{ {
byte[] data = MiscellaneousUtils.HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00"); byte[] data = MiscellaneousUtils.HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00");
@@ -217,7 +217,7 @@ namespace Newtonsoft.Json.Tests.Converters
[Test] [Test]
public void DeserializeNullToNonNullable() public void DeserializeNullToNonNullable()
{ {
ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime.", ExceptionAssert.Throws<JsonSerializationException>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() => () =>
{ {
DateTimeTestClass c2 = DateTimeTestClass c2 =
@@ -100,7 +100,7 @@ namespace Newtonsoft.Json.Tests.Converters
[Test] [Test]
public void DeserializeNullToNonNullable() public void DeserializeNullToNonNullable()
{ {
ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime.", ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() => () =>
{ {
DateTimeTestClass c2 = DateTimeTestClass c2 =
@@ -491,17 +491,25 @@ namespace Newtonsoft.Json.Tests.Converters
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "XmlNodeConverter can only convert JSON that begins with an object.")]
public void NoRootObject() public void NoRootObject()
{
ExceptionAssert.Throws<JsonSerializationException>(
"XmlNodeConverter can only convert JSON that begins with an object.",
() =>
{ {
XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"[1]"); XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"[1]");
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "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.")]
public void RootObjectMultipleProperties() public void RootObjectMultipleProperties()
{
ExceptionAssert.Throws<JsonSerializationException>(
"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.",
() =>
{ {
XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}");
});
} }
[Test] [Test]
@@ -613,22 +621,30 @@ namespace Newtonsoft.Json.Tests.Converters
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "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.")]
public void MultipleRootPropertiesXmlDocument() public void MultipleRootPropertiesXmlDocument()
{ {
string json = @"{""count"": 773840,""photos"": null}"; string json = @"{""count"": 773840,""photos"": null}";
ExceptionAssert.Throws<JsonSerializationException>(
"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.",
() =>
{
JsonConvert.DeserializeXmlNode(json); JsonConvert.DeserializeXmlNode(json);
});
} }
#if !NET20 #if !NET20
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "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.")]
public void MultipleRootPropertiesXDocument() public void MultipleRootPropertiesXDocument()
{ {
string json = @"{""count"": 773840,""photos"": null}"; string json = @"{""count"": 773840,""photos"": null}";
ExceptionAssert.Throws<JsonSerializationException>(
"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.",
() =>
{
JsonConvert.DeserializeXNode(json); JsonConvert.DeserializeXNode(json);
});
} }
#endif #endif
@@ -1008,7 +1024,6 @@ namespace Newtonsoft.Json.Tests.Converters
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "XmlNodeConverter cannot convert JSON with an empty property name to XML.")]
public void EmptyPropertyName() public void EmptyPropertyName()
{ {
string json = @"{ string json = @"{
@@ -1090,7 +1105,12 @@ namespace Newtonsoft.Json.Tests.Converters
} }
}"; }";
ExceptionAssert.Throws<JsonSerializationException>(
"XmlNodeConverter cannot convert JSON with an empty property name to XML.",
() =>
{
DeserializeXmlNode(json); DeserializeXmlNode(json);
});
} }
[Test] [Test]
+1 -1
View File
@@ -303,7 +303,7 @@ now brown cow?", '"', true);
[Test] [Test]
public void TestInvalidStrings() public void TestInvalidStrings()
{ {
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: t. Line 1, position 19.", ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.",
() => () =>
{ {
string orig = @"this is a string ""that has quotes"" "; string orig = @"this is a string ""that has quotes"" ";
+170 -159
View File
@@ -189,11 +189,6 @@ namespace Newtonsoft.Json.Tests
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2."
#endif
)]
public void ParseAdditionalContent_Comma() public void ParseAdditionalContent_Comma()
{ {
string json = @"[ string json = @"[
@@ -203,17 +198,18 @@ namespace Newtonsoft.Json.Tests
],"; ],";
JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.",
() =>
{
while (reader.Read()) while (reader.Read())
{ {
} }
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Additional text encountered after finished reading JSON content: c. Line 5, position 2."
#endif
)]
public void ParseAdditionalContent_Text() public void ParseAdditionalContent_Text()
{ {
string json = @"[ string json = @"[
@@ -240,7 +236,12 @@ namespace Newtonsoft.Json.Tests
reader.Read(); reader.Read();
Assert.AreEqual(5, reader.LineNumber); Assert.AreEqual(5, reader.LineNumber);
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: c. Path '', line 5, position 2.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -261,19 +262,20 @@ namespace Newtonsoft.Json.Tests
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Additional text encountered after finished reading JSON content: a. Line 1, position 5."
#endif
)]
public void ParseAdditionalContent_WhitespaceThenText() public void ParseAdditionalContent_WhitespaceThenText()
{ {
string json = @"'hi' a"; string json = @"'hi' a";
JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: a. Path '', line 1, position 5.",
() =>
{
while (reader.Read()) while (reader.Read())
{ {
} }
});
} }
[Test] [Test]
@@ -483,27 +485,28 @@ namespace Newtonsoft.Json.Tests
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentNullException)
#if !NETFX_CORE
, ExpectedMessage = @"Value cannot be null.
Parameter name: reader"
#endif
)]
public void NullTextReader() public void NullTextReader()
{
ExceptionAssert.Throws<ArgumentNullException>(
@"Value cannot be null.
Parameter name: reader",
() =>
{ {
new JsonTextReader(null); new JsonTextReader(null);
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3."
#endif
)]
public void UnexpectedEndOfString() public void UnexpectedEndOfString()
{ {
JsonReader reader = new JsonTextReader(new StringReader("'hi")); JsonReader reader = new JsonTextReader(new StringReader("'hi"));
ExceptionAssert.Throws<JsonReaderException>(
"Unterminated string. Expected delimiter: '. Path '', line 1, position 3.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -664,54 +667,58 @@ Parameter name: reader"
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end while parsing unicode character. Line 1, position 4."
#endif
)]
public void UnexpectedEndOfHex() public void UnexpectedEndOfHex()
{ {
JsonReader reader = new JsonTextReader(new StringReader(@"'h\u123")); JsonReader reader = new JsonTextReader(new StringReader(@"'h\u123"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing unicode character. Path '', line 1, position 4.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3."
#endif
)]
public void UnexpectedEndOfControlCharacter() public void UnexpectedEndOfControlCharacter()
{ {
JsonReader reader = new JsonTextReader(new StringReader(@"'h\")); JsonReader reader = new JsonTextReader(new StringReader(@"'h\"));
ExceptionAssert.Throws<JsonReaderException>(
"Unterminated string. Expected delimiter: '. Path '', line 1, position 3.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading bytes. Unexpected token: Boolean. Line 1, position 4."
#endif
)]
public void ReadBytesWithBadCharacter() public void ReadBytesWithBadCharacter()
{ {
JsonReader reader = new JsonTextReader(new StringReader(@"true")); JsonReader reader = new JsonTextReader(new StringReader(@"true"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading bytes. Unexpected token: Boolean. Path '', line 1, position 4.",
() =>
{
reader.ReadAsBytes(); reader.ReadAsBytes();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 17."
#endif
)]
public void ReadBytesWithUnexpectedEnd() public void ReadBytesWithUnexpectedEnd()
{ {
string helloWorld = "Hello world!"; string helloWorld = "Hello world!";
byte[] helloWorldData = Encoding.UTF8.GetBytes(helloWorld); byte[] helloWorldData = Encoding.UTF8.GetBytes(helloWorld);
JsonReader reader = new JsonTextReader(new StringReader(@"'" + Convert.ToBase64String(helloWorldData))); JsonReader reader = new JsonTextReader(new StringReader(@"'" + Convert.ToBase64String(helloWorldData)));
ExceptionAssert.Throws<JsonReaderException>(
"Unterminated string. Expected delimiter: '. Path '', line 1, position 17.",
() =>
{
reader.ReadAsBytes(); reader.ReadAsBytes();
});
} }
[Test] [Test]
@@ -725,16 +732,17 @@ Parameter name: reader"
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end while parsing unquoted property name. Line 1, position 4."
#endif
)]
public void UnexpectedEndWhenParsingUnquotedProperty() public void UnexpectedEndWhenParsingUnquotedProperty()
{ {
JsonReader reader = new JsonTextReader(new StringReader(@"{aww")); JsonReader reader = new JsonTextReader(new StringReader(@"{aww"));
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing unquoted property name. Path '', line 1, position 4.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -1193,11 +1201,6 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = @"Invalid character after parsing property name. Expected ':' but got: "". Line 3, position 9."
#endif
)]
public void MissingColon() public void MissingColon()
{ {
string json = @"{ string json = @"{
@@ -1215,7 +1218,12 @@ bye", reader.Value);
reader.Read(); reader.Read();
Assert.AreEqual(JsonToken.Boolean, reader.TokenType); Assert.AreEqual(JsonToken.Boolean, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
@"Invalid character after parsing property name. Expected ':' but got: "". Path 'A', line 3, position 9.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -1289,17 +1297,18 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected character encountered while parsing value: }. Line 1, position 1."
#endif
)]
public void ReadBadCharInArray() public void ReadBadCharInArray()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"[}")); JsonTextReader reader = new JsonTextReader(new StringReader(@"[}"));
reader.Read(); reader.Read();
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected character encountered while parsing value: }. Path '', line 1, position 1.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -1321,16 +1330,16 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 1."
#endif
)]
public void ReadAsBytesNoContentWrappedObject() public void ReadAsBytesNoContentWrappedObject()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"{")); JsonTextReader reader = new JsonTextReader(new StringReader(@"{"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end when reading bytes. Path '', line 1, position 1.",
() =>
{
reader.ReadAsBytes(); reader.ReadAsBytes();
});
} }
#if !NET20 #if !NET20
@@ -1345,44 +1354,43 @@ bye", reader.Value);
#endif #endif
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading decimal. Unexpected token: StartConstructor. Line 1, position 9."
#endif
)]
public void ReadAsDecimalBadContent() public void ReadAsDecimalBadContent()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()"));
Assert.IsNull(reader.ReadAsDecimal()); ExceptionAssert.Throws<JsonReaderException>(
Assert.AreEqual(JsonToken.None, reader.TokenType); "Error reading decimal. Unexpected token: StartConstructor. Path '', line 1, position 9.",
() =>
{
reader.ReadAsDecimal();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading bytes. Unexpected token: StartConstructor. Line 1, position 9."
#endif
)]
public void ReadAsBytesBadContent() public void ReadAsBytesBadContent()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading bytes. Unexpected token: StartConstructor. Path '', line 1, position 9.",
() =>
{
reader.ReadAsBytes(); reader.ReadAsBytes();
});
} }
#if !NET20 #if !NET20
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading date. Unexpected token: StartConstructor. Line 1, position 9."
#endif
)]
public void ReadAsDateTimeOffsetBadContent() public void ReadAsDateTimeOffsetBadContent()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()"));
ExceptionAssert.Throws<JsonReaderException>(
"Error reading date. Unexpected token: StartConstructor. Path '', line 1, position 9.",
() =>
{
reader.ReadAsDateTimeOffset(); reader.ReadAsDateTimeOffset();
});
} }
#endif #endif
@@ -1398,29 +1406,29 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 2."
#endif
)]
public void ReadAsBytesIntegerArrayWithNoEnd() public void ReadAsBytesIntegerArrayWithNoEnd()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"[1")); JsonTextReader reader = new JsonTextReader(new StringReader(@"[1"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end when reading bytes. Path '[0]', line 1, position 2.",
() =>
{
reader.ReadAsBytes(); reader.ReadAsBytes();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected token when reading bytes: Float. Line 1, position 4."
#endif
)]
public void ReadAsBytesArrayWithBadContent() public void ReadAsBytesArrayWithBadContent()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"[1.0]")); JsonTextReader reader = new JsonTextReader(new StringReader(@"[1.0]"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected token when reading bytes: Float. Path '[0]', line 1, position 4.",
() =>
{
reader.ReadAsBytes(); reader.ReadAsBytes();
});
} }
[Test] [Test]
@@ -1515,11 +1523,6 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22."
#endif
)]
public void ReadAsDateTimeOffsetBadString() public void ReadAsDateTimeOffsetBadString()
{ {
string json = @"{""Offset"":""blablahbla""}"; string json = @"{""Offset"":""blablahbla""}";
@@ -1532,7 +1535,12 @@ bye", reader.Value);
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.",
() =>
{
reader.ReadAsDateTimeOffset(); reader.ReadAsDateTimeOffset();
});
} }
[Test] [Test]
@@ -1672,11 +1680,6 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(FormatException)
#if !NETFX_CORE
, ExpectedMessage = "Input string was not in a correct format."
#endif
)]
public void ReadAsIntDecimal() public void ReadAsIntDecimal()
{ {
string json = @"{""Name"": 1.1}"; string json = @"{""Name"": 1.1}";
@@ -1689,70 +1692,77 @@ bye", reader.Value);
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<FormatException>(
"Input string was not in a correct format.",
() =>
{
reader.ReadAsInt32(); reader.ReadAsInt32();
Assert.AreEqual(JsonToken.Integer, reader.TokenType); });
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error parsing null value. Line 0, position 0."
#endif
)]
public void MatchWithInsufficentCharacters() public void MatchWithInsufficentCharacters()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"nul")); JsonTextReader reader = new JsonTextReader(new StringReader(@"nul"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing null value. Path '', line 0, position 0.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error parsing null value. Line 0, position 0."
#endif
)]
public void MatchWithWrongCharacters() public void MatchWithWrongCharacters()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz")); JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing null value. Path '', line 0, position 0.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error parsing null value. Line 1, position 4."
#endif
)]
public void MatchWithNoTrailingSeperator() public void MatchWithNoTrailingSeperator()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz")); JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing null value. Path '', line 1, position 4.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6."
#endif
)]
public void UnclosedComment() public void UnclosedComment()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf")); JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf"));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing comment. Path '', line 1, position 6.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error parsing comment. Expected: *, got s. Line 1, position 1."
#endif
)]
public void BadCommentStart() public void BadCommentStart()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf")); JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing comment. Expected: *, got s. Path '', line 1, position 1.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -1924,31 +1934,31 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end while parsing constructor. Line 1, position 7."
#endif
)]
public void ParseConstructorWithUnexpectedEnd() public void ParseConstructorWithUnexpectedEnd()
{ {
string json = "new Dat"; string json = "new Dat";
JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end while parsing constructor. Path '', line 1, position 7.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected character while parsing constructor: !. Line 1, position 9."
#endif
)]
public void ParseConstructorWithUnexpectedCharacter() public void ParseConstructorWithUnexpectedCharacter()
{ {
string json = "new Date !"; string json = "new Date !";
JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected character while parsing constructor: !. Path '', line 1, position 9.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -1990,16 +2000,16 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error parsing boolean value. Line 1, position 4."
#endif
)]
public void ParseIncompleteCommentSeperator() public void ParseIncompleteCommentSeperator()
{ {
JsonTextReader reader = new JsonTextReader(new StringReader("true/")); JsonTextReader reader = new JsonTextReader(new StringReader("true/"));
ExceptionAssert.Throws<JsonReaderException>(
"Error parsing boolean value. Path '', line 1, position 4.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -2016,17 +2026,17 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected character while parsing constructor: ,. Line 1, position 8."
#endif
)]
public void ParseConstructorWithBadCharacter() public void ParseConstructorWithBadCharacter()
{ {
string json = "new Date,()"; string json = "new Date,()";
JsonTextReader reader = new JsonTextReader(new StringReader(json)); JsonTextReader reader = new JsonTextReader(new StringReader(json));
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected character while parsing constructor: ,. Path '', line 1, position 8.",
() =>
{
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
});
} }
[Test] [Test]
@@ -2181,17 +2191,18 @@ bye", reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Additional text encountered after finished reading JSON content: }. Line 1, position 2."
#endif
)]
public void UnexpectedEndTokenWhenParsingOddEndToken() public void UnexpectedEndTokenWhenParsingOddEndToken()
{ {
JsonReader reader = new JsonTextReader(new StringReader(@"{}}")); JsonReader reader = new JsonTextReader(new StringReader(@"{}}"));
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: }. Path '', line 1, position 2.",
() =>
{
reader.Read(); reader.Read();
});
} }
[Test] [Test]
@@ -2275,7 +2286,7 @@ bye", reader.Value);
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
ExceptionAssert.Throws<JsonReaderException>( ExceptionAssert.Throws<JsonReaderException>(
"The reader's MaxDepth of 1 has been exceeded. Line 1, position 2.", "The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.",
() => () =>
{ {
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
@@ -2296,7 +2307,7 @@ bye", reader.Value);
Assert.AreEqual(0, reader.Depth); Assert.AreEqual(0, reader.Depth);
ExceptionAssert.Throws<JsonReaderException>( ExceptionAssert.Throws<JsonReaderException>(
"The reader's MaxDepth of 1 has been exceeded. Line 1, position 2.", "The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.",
() => () =>
{ {
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
@@ -2319,7 +2330,7 @@ bye", reader.Value);
Assert.AreEqual(1, reader.Depth); Assert.AreEqual(1, reader.Depth);
ExceptionAssert.Throws<JsonReaderException>( ExceptionAssert.Throws<JsonReaderException>(
"The reader's MaxDepth of 1 has been exceeded. Line 1, position 9.", "The reader's MaxDepth of 1 has been exceeded. Path '[1]', line 1, position 9.",
() => () =>
{ {
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
+15 -15
View File
@@ -172,12 +172,11 @@ namespace Newtonsoft.Json.Tests
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation."
#endif
)]
public void WriteValueObjectWithUnsupportedValue() public void WriteValueObjectWithUnsupportedValue()
{
ExceptionAssert.Throws<ArgumentException>(
@"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.",
() =>
{ {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
@@ -186,6 +185,7 @@ namespace Newtonsoft.Json.Tests
jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteValue(new Version(1, 1, 1, 1));
jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray();
} }
});
} }
[Test] [Test]
@@ -594,12 +594,11 @@ namespace Newtonsoft.Json.Tests
} }
[Test] [Test]
[ExpectedException(typeof(JsonWriterException)
#if !NETFX_CORE
, ExpectedMessage = "No token to close."
#endif
)]
public void BadWriteEndArray() public void BadWriteEndArray()
{
ExceptionAssert.Throws<JsonWriterException>(
"No token to close.",
() =>
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb); StringWriter sw = new StringWriter(sb);
@@ -613,15 +612,15 @@ namespace Newtonsoft.Json.Tests
jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray();
jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray();
} }
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."
#endif
)]
public void InvalidQuoteChar() public void InvalidQuoteChar()
{
ExceptionAssert.Throws<ArgumentException>(
@"Invalid JavaScript string quote character. Valid quote characters are ' and "".",
() =>
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb); StringWriter sw = new StringWriter(sb);
@@ -631,6 +630,7 @@ namespace Newtonsoft.Json.Tests
jsonWriter.Formatting = Formatting.Indented; jsonWriter.Formatting = Formatting.Indented;
jsonWriter.QuoteChar = '*'; jsonWriter.QuoteChar = '*';
} }
});
} }
[Test] [Test]
@@ -86,16 +86,16 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = "Could not determine JSON object type for type System.String[]."
#endif
)]
public void JObjectPropertyNameWithNonToken() public void JObjectPropertyNameWithNonToken()
{
ExceptionAssert.Throws<ArgumentException>(
"Could not determine JSON object type for type System.String[].",
() =>
{ {
dynamic d = new JObject(); dynamic d = new JObject();
d.First = new [] {"One", "II", "3"}; d.First = new[] { "One", "II", "3" };
});
} }
[Test] [Test]
+99 -91
View File
@@ -23,7 +23,7 @@ namespace Newtonsoft.Json.Tests.Linq
[Test] [Test]
public void Clear() public void Clear()
{ {
JArray a = new JArray { 1 }; JArray a = new JArray {1};
Assert.AreEqual(1, a.Count); Assert.AreEqual(1, a.Count);
a.Clear(); a.Clear();
@@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Tests.Linq
{ {
JValue v = new JValue(1); JValue v = new JValue(1);
JArray a = new JArray { v }; JArray a = new JArray {v};
Assert.AreEqual(false, a.Contains(new JValue(2))); Assert.AreEqual(false, a.Contains(new JValue(2)));
Assert.AreEqual(false, a.Contains(new JValue(1))); Assert.AreEqual(false, a.Contains(new JValue(1)));
@@ -63,64 +63,62 @@ namespace Newtonsoft.Json.Tests.Linq
JToken[] a = new JToken[5]; JToken[] a = new JToken[5];
((ICollection<JToken>)j).CopyTo(a, 1); ((ICollection<JToken>) j).CopyTo(a, 1);
Assert.AreEqual(null, a[0]); Assert.AreEqual(null, a[0]);
Assert.AreEqual(1, (int)a[1]); Assert.AreEqual(1, (int) a[1]);
Assert.AreEqual(2, (int)a[2]); Assert.AreEqual(2, (int) a[2]);
Assert.AreEqual(3, (int)a[3]); Assert.AreEqual(3, (int) a[3]);
Assert.AreEqual(null, a[4]); Assert.AreEqual(null, a[4]);
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentNullException)
#if !NETFX_CORE
, ExpectedMessage = @"Value cannot be null.
Parameter name: array"
#endif
)]
public void GenericCollectionCopyToNullArrayShouldThrow() public void GenericCollectionCopyToNullArrayShouldThrow()
{ {
JArray j = new JArray(); JArray j = new JArray();
((ICollection<JToken>)j).CopyTo(null, 0);
ExceptionAssert.Throws<ArgumentNullException>(
@"Value cannot be null.
Parameter name: array",
() =>
{
((ICollection<JToken>) j).CopyTo(null, 0);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"arrayIndex is less than 0.
Parameter name: arrayIndex"
#endif
)]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{ {
JArray j = new JArray(); JArray j = new JArray();
((ICollection<JToken>)j).CopyTo(new JToken[1], -1);
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"arrayIndex is less than 0.
Parameter name: arrayIndex",
() =>
{
((ICollection<JToken>) j).CopyTo(new JToken[1], -1);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"arrayIndex is equal to or greater than the length of array."
#endif
)]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{ {
JArray j = new JArray(); JArray j = new JArray();
((ICollection<JToken>)j).CopyTo(new JToken[1], 1);
ExceptionAssert.Throws<ArgumentException>(
@"arrayIndex is equal to or greater than the length of array.",
() =>
{
((ICollection<JToken>) j).CopyTo(new JToken[1], 1);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."
#endif
)]
public void GenericCollectionCopyToInsufficientArrayCapacity() public void GenericCollectionCopyToInsufficientArrayCapacity()
{ {
JArray j = new JArray(); JArray j = new JArray();
@@ -128,7 +126,12 @@ Parameter name: arrayIndex"
j.Add(new JValue(2)); j.Add(new JValue(2));
j.Add(new JValue(3)); j.Add(new JValue(3));
ExceptionAssert.Throws<ArgumentException>(
@"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.",
() =>
{
((ICollection<JToken>)j).CopyTo(new JToken[3], 1); ((ICollection<JToken>)j).CopyTo(new JToken[3], 1);
});
} }
[Test] [Test]
@@ -200,29 +203,31 @@ Parameter name: arrayIndex"
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"Index is equal to or greater than Count.
Parameter name: index"
#endif
)]
public void RemoveAtOutOfRangeIndexShouldError() public void RemoveAtOutOfRangeIndexShouldError()
{ {
JArray j = new JArray(); JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index is equal to or greater than Count.
Parameter name: index",
() =>
{
j.RemoveAt(0); j.RemoveAt(0);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"Index is less than 0.
Parameter name: index"
#endif
)]
public void RemoveAtNegativeIndexShouldError() public void RemoveAtNegativeIndexShouldError()
{ {
JArray j = new JArray(); JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index is less than 0.
Parameter name: index",
() =>
{
j.RemoveAt(-1); j.RemoveAt(-1);
});
} }
[Test] [Test]
@@ -292,33 +297,35 @@ Parameter name: index"
JArray j = new JArray(); JArray j = new JArray();
j.Insert(0, null); j.Insert(0, null);
Assert.AreEqual(null, ((JValue)j[0]).Value); Assert.AreEqual(null, ((JValue) j[0]).Value);
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
#endif
)]
public void InsertNegativeIndexShouldThrow() public void InsertNegativeIndexShouldThrow()
{ {
JArray j = new JArray(); JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index",
() =>
{
j.Insert(-1, new JValue(1)); j.Insert(-1, new JValue(1));
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"Index must be within the bounds of the List.
Parameter name: index"
#endif
)]
public void InsertOutOfRangeIndexShouldThrow() public void InsertOutOfRangeIndexShouldThrow()
{ {
JArray j = new JArray(); JArray j = new JArray();
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"Index must be within the bounds of the List.
Parameter name: index",
() =>
{
j.Insert(2, new JValue(1)); j.Insert(2, new JValue(1));
});
} }
[Test] [Test]
@@ -344,15 +351,16 @@ Parameter name: index"
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject"
#endif
)]
public void Parse_ShouldThrowOnUnexpectedToken() public void Parse_ShouldThrowOnUnexpectedToken()
{ {
string json = @"{""prop"":""value""}"; string json = @"{""prop"":""value""}";
ExceptionAssert.Throws<JsonReaderException>(
"Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.",
() =>
{
JArray.Parse(json); JArray.Parse(json);
});
} }
public class ListItemFields public class ListItemFields
@@ -368,9 +376,9 @@ Parameter name: index"
IEnumerable<ListItemFields> t = new List<ListItemFields> IEnumerable<ListItemFields> t = new List<ListItemFields>
{ {
new ListItemFields { ListItemText = "First", ListItemValue = 1 }, new ListItemFields {ListItemText = "First", ListItemValue = 1},
new ListItemFields { ListItemText = "Second", ListItemValue = 2 }, new ListItemFields {ListItemText = "Second", ListItemValue = 2},
new ListItemFields { ListItemText = "Third", ListItemValue = 3 } new ListItemFields {ListItemText = "Third", ListItemValue = 3}
}; };
JObject optionValues = JObject optionValues =
@@ -418,7 +426,7 @@ Parameter name: index"
int i = 1; int i = 1;
foreach (JToken token in a) foreach (JToken token in a)
{ {
Assert.AreEqual(i, (int)token); Assert.AreEqual(i, (int) token);
i++; i++;
} }
} }
@@ -447,21 +455,21 @@ Parameter name: index"
a.Add(a); a.Add(a);
Assert.AreEqual(3, a.Count); Assert.AreEqual(3, a.Count);
Assert.AreEqual(1, (int)a[0]); Assert.AreEqual(1, (int) a[0]);
Assert.AreEqual(2, (int)a[1]); Assert.AreEqual(2, (int) a[1]);
Assert.AreNotSame(a, a[2]); Assert.AreNotSame(a, a[2]);
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"Set JArray values with invalid key value: ""badvalue"". Array position index expected."
#endif
)]
public void SetValueWithInvalidIndex() public void SetValueWithInvalidIndex()
{
ExceptionAssert.Throws<ArgumentException>(
@"Set JArray values with invalid key value: ""badvalue"". Array position index expected.",
() =>
{ {
JArray a = new JArray(); JArray a = new JArray();
a["badvalue"] = new JValue(3); a["badvalue"] = new JValue(3);
});
} }
[Test] [Test]
@@ -469,35 +477,35 @@ Parameter name: index"
{ {
object key = 0; object key = 0;
JArray a = new JArray((object)null); JArray a = new JArray((object) null);
a[key] = new JValue(3); a[key] = new JValue(3);
Assert.AreEqual(3, (int)a[key]); Assert.AreEqual(3, (int) a[key]);
} }
[Test] [Test]
public void ReplaceAll() public void ReplaceAll()
{ {
JArray a = new JArray(new [] { 1, 2, 3 }); JArray a = new JArray(new[] {1, 2, 3});
Assert.AreEqual(3, a.Count); Assert.AreEqual(3, a.Count);
Assert.AreEqual(1, (int)a[0]); Assert.AreEqual(1, (int) a[0]);
Assert.AreEqual(2, (int)a[1]); Assert.AreEqual(2, (int) a[1]);
Assert.AreEqual(3, (int)a[2]); Assert.AreEqual(3, (int) a[2]);
a.ReplaceAll(1); a.ReplaceAll(1);
Assert.AreEqual(1, a.Count); Assert.AreEqual(1, a.Count);
Assert.AreEqual(1, (int)a[0]); Assert.AreEqual(1, (int) a[0]);
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected end of content while loading JArray."
#endif
)]
public void ParseIncomplete() public void ParseIncomplete()
{
ExceptionAssert.Throws<JsonReaderException>(
"Unexpected end of content while loading JArray. Path '[0]', line 1, position 2.",
() =>
{ {
JArray.Parse("[1"); JArray.Parse("[1");
});
} }
[Test] [Test]
@@ -508,16 +516,11 @@ Parameter name: index"
array.Insert(1, 456); array.Insert(1, 456);
Assert.AreEqual(2, array.Count); Assert.AreEqual(2, array.Count);
Assert.AreEqual(123, (int)array[0]); Assert.AreEqual(123, (int) array[0]);
Assert.AreEqual(456, (int)array[1]); Assert.AreEqual(456, (int) array[1]);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2."
#endif
)]
public void ParseAdditionalContent() public void ParseAdditionalContent()
{ {
string json = @"[ string json = @"[
@@ -526,7 +529,12 @@ Parameter name: index"
""Large"" ""Large""
], 987987"; ], 987987";
ExceptionAssert.Throws<JsonReaderException>(
"Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.",
() =>
{
JArray.Parse(json); JArray.Parse(json);
});
} }
} }
} }
+54 -40
View File
@@ -113,16 +113,16 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."
#endif
)]
public void DuplicatePropertyNameShouldThrow() public void DuplicatePropertyNameShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.",
() =>
{ {
JObject o = new JObject(); JObject o = new JObject();
o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null);
});
} }
[Test] [Test]
@@ -227,50 +227,49 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentNullException)
#if !NETFX_CORE
, ExpectedMessage = @"Value cannot be null.
Parameter name: array"
#endif
)]
public void GenericCollectionCopyToNullArrayShouldThrow() public void GenericCollectionCopyToNullArrayShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
@"Value cannot be null.
Parameter name: array",
() =>
{ {
JObject o = new JObject(); JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"arrayIndex is less than 0.
Parameter name: arrayIndex"
#endif
)]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
ExceptionAssert.Throws<ArgumentOutOfRangeException>(
@"arrayIndex is less than 0.
Parameter name: arrayIndex",
() =>
{ {
JObject o = new JObject(); JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"arrayIndex is equal to or greater than the length of array."
#endif
)]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(
@"arrayIndex is equal to or greater than the length of array.",
() =>
{ {
JObject o = new JObject(); JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
});
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."
#endif
)]
public void GenericCollectionCopyToInsufficientArrayCapacity() public void GenericCollectionCopyToInsufficientArrayCapacity()
{
ExceptionAssert.Throws<ArgumentException>(
@"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.",
() =>
{ {
JObject o = new JObject(); JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue", new JValue(1));
@@ -278,6 +277,7 @@ Parameter name: arrayIndex"
o.Add("PropertyNameValue3", new JValue(3)); o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
});
} }
[Test] [Test]
@@ -363,7 +363,7 @@ Parameter name: arrayIndex"
[Test] [Test]
public void Parse_ShouldThrowOnUnexpectedToken() public void Parse_ShouldThrowOnUnexpectedToken()
{ {
ExceptionAssert.Throws<Exception>("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray", ExceptionAssert.Throws<JsonReaderException>("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.",
() => () =>
{ {
string json = @"[""prop""]"; string json = @"[""prop""]";
@@ -400,15 +400,13 @@ Parameter name: arrayIndex"
public void Blog() public void Blog()
{ {
ExceptionAssert.Throws<JsonReaderException>( ExceptionAssert.Throws<JsonReaderException>(
"Invalid property identifier character: ]. Line 3, position 5.", "Invalid property identifier character: ]. Path 'name', line 3, position 5.",
() => () =>
{ {
JObject person = JObject.Parse(@"{ JObject.Parse(@"{
""name"": ""James"", ""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}] ]!#$THIS IS: BAD JSON![{}}}}]
}"); }");
// Invalid property identifier character: ]. Line 3, position 9.
}); });
} }
@@ -1271,19 +1269,27 @@ Parameter name: arrayIndex"
} }
[Test] [Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListApplySort() public void IBindingListApplySort()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{ {
IBindingList l = new JObject(); IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending); l.ApplySort(null, ListSortDirection.Ascending);
});
} }
[Test] [Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListRemoveSort() public void IBindingListRemoveSort()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{ {
IBindingList l = new JObject(); IBindingList l = new JObject();
l.RemoveSort(); l.RemoveSort();
});
} }
[Test] [Test]
@@ -1295,11 +1301,15 @@ Parameter name: arrayIndex"
} }
[Test] [Test]
[ExpectedException(typeof(NotSupportedException))]
public void IBindingListFind() public void IBindingListFind()
{
ExceptionAssert.Throws<NotSupportedException>(
"Specified method is not supported.",
() =>
{ {
IBindingList l = new JObject(); IBindingList l = new JObject();
l.Find(null, null); l.Find(null, null);
});
} }
[Test] [Test]
@@ -1310,11 +1320,15 @@ Parameter name: arrayIndex"
} }
[Test] [Test]
[ExpectedException(typeof(Exception), ExpectedMessage = "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.")]
public void IBindingListAddNew() public void IBindingListAddNew()
{
ExceptionAssert.Throws<JsonException>(
"Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.",
() =>
{ {
IBindingList l = new JObject(); IBindingList l = new JObject();
l.AddNew(); l.AddNew();
});
} }
[Test] [Test]
@@ -1580,7 +1594,7 @@ Parameter name: arrayIndex"
[Test] [Test]
public void NumberTooBigForInt64() public void NumberTooBigForInt64()
{ {
ExceptionAssert.Throws<JsonReaderException>("JSON integer 307953220000517141511 is too large or small for an Int64. Line 1, position 30.", ExceptionAssert.Throws<JsonReaderException>("JSON integer 307953220000517141511 is too large or small for an Int64. Path 'code', line 1, position 30.",
() => () =>
{ {
string json = @"{""code"": 307953220000517141511}"; string json = @"{""code"": 307953220000517141511}";
@@ -1592,7 +1606,7 @@ Parameter name: arrayIndex"
[Test] [Test]
public void ParseIncomplete() public void ParseIncomplete()
{ {
ExceptionAssert.Throws<Exception>("Unexpected end of content while loading JObject.", ExceptionAssert.Throws<Exception>("Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.",
() => () =>
{ {
JObject.Parse("{ foo:"); JObject.Parse("{ foo:");
@@ -1631,7 +1645,7 @@ Parameter name: arrayIndex"
[Test] [Test]
public void LoadFromNestedObjectIncomplete() public void LoadFromNestedObjectIncomplete()
{ {
ExceptionAssert.Throws<Exception>("Unexpected end of content while loading JObject.", ExceptionAssert.Throws<JsonReaderException>("Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15.",
() => () =>
{ {
string jsonText = @"{ string jsonText = @"{
@@ -1729,7 +1743,7 @@ Parameter name: arrayIndex"
[Test] [Test]
public void ParseAdditionalContent() public void ParseAdditionalContent()
{ {
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Line 10, position 2.", ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2.",
() => () =>
{ {
string json = @"{ string json = @"{
+50 -50
View File
@@ -59,25 +59,25 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = @"Unexpected character while parsing path indexer: ["
#endif
)]
public void BadCharactersInIndexer() public void BadCharactersInIndexer()
{
ExceptionAssert.Throws<JsonException>(
@"Unexpected character while parsing path indexer: [",
() =>
{ {
new JPath("Blah[[0]].Two.Three[1].Four"); new JPath("Blah[[0]].Two.Three[1].Four");
});
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = @"Path ended with open indexer. Expected ]"
#endif
)]
public void UnclosedIndexer() public void UnclosedIndexer()
{
ExceptionAssert.Throws<JsonException>(
@"Path ended with open indexer. Expected ]",
() =>
{ {
new JPath("Blah[0"); new JPath("Blah[0");
});
} }
[Test] [Test]
@@ -102,25 +102,25 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Empty path indexer."
#endif
)]
public void EmptyIndexer() public void EmptyIndexer()
{
ExceptionAssert.Throws<JsonException>(
"Empty path indexer.",
() =>
{ {
new JPath("[]"); new JPath("[]");
});
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected character while parsing path: ]"
#endif
)]
public void IndexerCloseInProperty() public void IndexerCloseInProperty()
{
ExceptionAssert.Throws<JsonException>(
"Unexpected character while parsing path: ]",
() =>
{ {
new JPath("]"); new JPath("]");
});
} }
[Test] [Test]
@@ -135,14 +135,14 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Unexpected character following indexer: B"
#endif
)]
public void MissingDotAfterIndexer() public void MissingDotAfterIndexer()
{
ExceptionAssert.Throws<JsonException>(
"Unexpected character following indexer: B",
() =>
{ {
new JPath("[1]Blah"); new JPath("[1]Blah");
});
} }
[Test] [Test]
@@ -178,17 +178,17 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = @"Index 1 not valid on JObject."
#endif
)]
public void EvaluateIndexerOnObjectWithError() public void EvaluateIndexerOnObjectWithError()
{ {
JObject o = new JObject( JObject o = new JObject(
new JProperty("Blah", 1)); new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
@"Index 1 not valid on JObject.",
() =>
{
o.SelectToken("[1]", true); o.SelectToken("[1]", true);
});
} }
[Test] [Test]
@@ -201,43 +201,43 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = @"Property 'BlahBlah' not valid on JArray."
#endif
)]
public void EvaluatePropertyOnArrayWithError() public void EvaluatePropertyOnArrayWithError()
{ {
JArray a = new JArray(1, 2, 3, 4, 5); JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<JsonException>(
@"Property 'BlahBlah' not valid on JArray.",
() =>
{
a.SelectToken("BlahBlah", true); a.SelectToken("BlahBlah", true);
});
} }
[Test] [Test]
[ExpectedException(typeof(IndexOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = @"Index 1 outside the bounds of JConstructor."
#endif
)]
public void EvaluateConstructorOutOfBoundsIndxerWithError() public void EvaluateConstructorOutOfBoundsIndxerWithError()
{ {
JConstructor c = new JConstructor("Blah"); JConstructor c = new JConstructor("Blah");
ExceptionAssert.Throws<IndexOutOfRangeException>(
@"Index 1 outside the bounds of JConstructor.",
() =>
{
c.SelectToken("[1]", true); c.SelectToken("[1]", true);
});
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Property 'Missing' does not exist on JObject."
#endif
)]
public void EvaluateMissingPropertyWithError() public void EvaluateMissingPropertyWithError()
{ {
JObject o = new JObject( JObject o = new JObject(
new JProperty("Blah", 1)); new JProperty("Blah", 1));
ExceptionAssert.Throws<JsonException>(
"Property 'Missing' does not exist on JObject.",
() =>
{
o.SelectToken("Missing", true); o.SelectToken("Missing", true);
});
} }
[Test] [Test]
@@ -250,16 +250,16 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(IndexOutOfRangeException)
#if !NETFX_CORE
, ExpectedMessage = "Index 1000 outside the bounds of JArray."
#endif
)]
public void EvaluateArrayOutOfBoundsIndxerWithError() public void EvaluateArrayOutOfBoundsIndxerWithError()
{ {
JArray a = new JArray(1, 2, 3, 4, 5); JArray a = new JArray(1, 2, 3, 4, 5);
ExceptionAssert.Throws<IndexOutOfRangeException>(
"Index 1000 outside the bounds of JArray.",
() =>
{
a.SelectToken("[1000].Ha", true); a.SelectToken("[1000].Ha", true);
});
} }
[Test] [Test]
@@ -64,45 +64,45 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty."
#endif
)]
public void IListClear() public void IListClear()
{ {
JProperty p = new JProperty("TestProperty", null); JProperty p = new JProperty("TestProperty", null);
IList l = p; IList l = p;
ExceptionAssert.Throws<JsonException>(
"Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.",
() =>
{
l.Clear(); l.Clear();
});
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values."
#endif
)]
public void IListAdd() public void IListAdd()
{ {
JProperty p = new JProperty("TestProperty", null); JProperty p = new JProperty("TestProperty", null);
IList l = p; IList l = p;
ExceptionAssert.Throws<JsonException>(
"Newtonsoft.Json.Linq.JProperty cannot have multiple values.",
() =>
{
l.Add(null); l.Add(null);
});
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty."
#endif
)]
public void IListRemove() public void IListRemove()
{ {
JProperty p = new JProperty("TestProperty", null); JProperty p = new JProperty("TestProperty", null);
IList l = p; IList l = p;
ExceptionAssert.Throws<JsonException>(
"Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.",
() =>
{
l.Remove(p.Value); l.Remove(p.Value);
});
} }
[Test] [Test]
@@ -136,25 +136,25 @@ namespace Newtonsoft.Json.Tests.Linq
[Test] [Test]
public void MultiContentConstructor() public void MultiContentConstructor()
{ {
JProperty p = new JProperty("error", new List<string> { "one", "two" }); JProperty p = new JProperty("error", new List<string> {"one", "two"});
JArray a = (JArray) p.Value; JArray a = (JArray) p.Value;
Assert.AreEqual(a.Count, 2); Assert.AreEqual(a.Count, 2);
Assert.AreEqual("one", (string)a[0]); Assert.AreEqual("one", (string) a[0]);
Assert.AreEqual("two", (string)a[1]); Assert.AreEqual("two", (string) a[1]);
} }
[Test] [Test]
[ExpectedException(typeof(Exception)
#if !NETFX_CORE
, ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values."
#endif
)]
public void IListGenericAdd() public void IListGenericAdd()
{ {
IList<JToken> t = new JProperty("error", new List<string> { "one", "two" }); IList<JToken> t = new JProperty("error", new List<string> {"one", "two"});
ExceptionAssert.Throws<JsonException>(
"Newtonsoft.Json.Linq.JProperty cannot have multiple values.",
() =>
{
t.Add(1); t.Add(1);
t.Add(2); });
} }
} }
} }
@@ -123,11 +123,6 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22."
#endif
)]
public void ReadAsDateTimeOffsetBadString() public void ReadAsDateTimeOffsetBadString()
{ {
string json = @"{""Offset"":""blablahbla""}"; string json = @"{""Offset"":""blablahbla""}";
@@ -142,15 +137,15 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.",
() =>
{
reader.ReadAsDateTimeOffset(); reader.ReadAsDateTimeOffset();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading date. Unexpected token: Boolean. Line 1, position 14."
#endif
)]
public void ReadAsDateTimeOffsetBoolean() public void ReadAsDateTimeOffsetBoolean()
{ {
string json = @"{""Offset"":true}"; string json = @"{""Offset"":true}";
@@ -165,7 +160,12 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14.",
() =>
{
reader.ReadAsDateTimeOffset(); reader.ReadAsDateTimeOffset();
});
} }
[Test] [Test]
@@ -311,7 +311,8 @@ namespace Newtonsoft.Json.Tests.Linq
[Test] [Test]
public void ReadBytesFailure() public void ReadBytesFailure()
{ {
ExceptionAssert.Throws<JsonReaderException>("Error reading bytes. Unexpected token: Integer.", ExceptionAssert.Throws<JsonReaderException>(
"Error reading bytes. Unexpected token: Integer. Path 'Test1'.",
() => () =>
{ {
JObject o = JObject o =
@@ -480,11 +481,6 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Could not convert string to integer: hi. Line 1, position 12."
#endif
)]
public void ReadAsInt32BadString() public void ReadAsInt32BadString()
{ {
string json = @"{""Name"":""hi""}"; string json = @"{""Name"":""hi""}";
@@ -499,18 +495,15 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to integer: hi. Path 'Name', line 1, position 12.",
() =>
{
reader.ReadAsInt32(); reader.ReadAsInt32();
Assert.AreEqual(JsonToken.Integer, reader.TokenType); });
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading integer. Unexpected token: Boolean. Line 1, position 12."
#endif
)]
public void ReadAsInt32Boolean() public void ReadAsInt32Boolean()
{ {
string json = @"{""Name"":true}"; string json = @"{""Name"":true}";
@@ -525,7 +518,12 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12.",
() =>
{
reader.ReadAsInt32(); reader.ReadAsInt32();
});
} }
[Test] [Test]
@@ -550,11 +548,6 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Could not convert string to decimal: blah. Line 1, position 14."
#endif
)]
public void ReadAsDecimalBadString() public void ReadAsDecimalBadString()
{ {
string json = @"{""Name"":""blah""}"; string json = @"{""Name"":""blah""}";
@@ -569,15 +562,15 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to decimal: blah. Path 'Name', line 1, position 14.",
() =>
{
reader.ReadAsDecimal(); reader.ReadAsDecimal();
});
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = "Error reading decimal. Unexpected token: Boolean. Line 1, position 12."
#endif
)]
public void ReadAsDecimalBoolean() public void ReadAsDecimalBoolean()
{ {
string json = @"{""Name"":true}"; string json = @"{""Name"":true}";
@@ -592,7 +585,12 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
ExceptionAssert.Throws<JsonReaderException>(
"Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12.",
() =>
{
reader.ReadAsDecimal(); reader.ReadAsDecimal();
});
} }
[Test] [Test]
@@ -565,15 +565,15 @@ namespace Newtonsoft.Json.Tests.Linq
} }
[Test] [Test]
[ExpectedException(typeof(ArgumentException)
#if !NETFX_CORE
, ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."
#endif
)]
public void AddValueToObject() public void AddValueToObject()
{
ExceptionAssert.Throws<ArgumentException>(
"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.",
() =>
{ {
JObject o = new JObject(); JObject o = new JObject();
o.Add(5); o.Add(5);
});
} }
[Test] [Test]
@@ -770,7 +770,7 @@ namespace Newtonsoft.Json.Tests.Linq
[Test] [Test]
public void ParseAdditionalContent() public void ParseAdditionalContent()
{ {
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Line 5, position 2.", ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.",
() => () =>
{ {
string json = @"[ string json = @"[
@@ -72,5 +72,5 @@ using System.Security;
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC #if !PocketPC
[assembly: AssemblyFileVersion("4.5.3.14818")] [assembly: AssemblyFileVersion("4.5.3.14821")]
#endif #endif
@@ -188,7 +188,7 @@ namespace Newtonsoft.Json.Tests.Serialization
[Test] [Test]
public void NoPublicDefaultConstructor() public void NoPublicDefaultConstructor()
{ {
ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.", ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.",
() => () =>
{ {
var settings = new JsonSerializerSettings(); var settings = new JsonSerializerSettings();
@@ -391,14 +391,14 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name."
#endif
)]
public void BadJsonPropertyClassSerialize() public void BadJsonPropertyClassSerialize()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.",
() =>
{ {
JsonConvert.SerializeObject(new BadJsonPropertyClass()); JsonConvert.SerializeObject(new BadJsonPropertyClass());
});
} }
[Test] [Test]
@@ -469,16 +469,16 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof (JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7."
#endif
)]
public void InvalidBackslash() public void InvalidBackslash()
{ {
string json = @"[""vvv\jvvv""]"; string json = @"[""vvv\jvvv""]";
ExceptionAssert.Throws<JsonReaderException>(
@"Bad JSON escape sequence: \j. Path '', line 1, position 7.",
() =>
{
JsonConvert.DeserializeObject<List<string>>(json); JsonConvert.DeserializeObject<List<string>>(json);
});
} }
[Test] [Test]
@@ -933,7 +933,7 @@ keyword such as type of business.""
Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json); Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json);
ExceptionAssert.Throws<JsonReaderException>( ExceptionAssert.Throws<JsonReaderException>(
"Could not convert string to DateTime: /Date(0)/. Line 1, position 33.", "Could not convert string to DateTime: /Date(0)/. Path 'DefaultConverter', line 1, position 33.",
() => () =>
{ {
JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings JsonConvert.DeserializeObject<MemberConverterClass>(json, new JsonSerializerSettings
@@ -1178,7 +1178,8 @@ keyword such as type of business.""
[Test] [Test]
public void DeserializeRequiredMembersClassNullRequiredValueProperty() public void DeserializeRequiredMembersClassNullRequiredValueProperty()
{ {
ExceptionAssert.Throws<JsonSerializationException>("Required property 'FirstName' expects a value but got null. Line 6, position 2.", ExceptionAssert.Throws<JsonSerializationException>(
"Required property 'FirstName' expects a value but got null. Path '', line 6, position 2.",
() => () =>
{ {
string json = @"{ string json = @"{
@@ -1195,7 +1196,8 @@ keyword such as type of business.""
[Test] [Test]
public void SerializeRequiredMembersClassNullRequiredValueProperty() public void SerializeRequiredMembersClassNullRequiredValueProperty()
{ {
ExceptionAssert.Throws<JsonSerializationException>("Cannot write a null value for property 'FirstName'. Property requires a value.", ExceptionAssert.Throws<JsonSerializationException>(
"Cannot write a null value for property 'FirstName'. Property requires a value.",
() => () =>
{ {
RequiredMembersClass requiredMembersClass = new RequiredMembersClass RequiredMembersClass requiredMembersClass = new RequiredMembersClass
@@ -1214,7 +1216,8 @@ keyword such as type of business.""
[Test] [Test]
public void RequiredMembersClassMissingRequiredProperty() public void RequiredMembersClassMissingRequiredProperty()
{ {
ExceptionAssert.Throws<JsonSerializationException>("Required property 'LastName' not found in JSON. Line 3, position 2.", ExceptionAssert.Throws<JsonSerializationException>(
"Required property 'LastName' not found in JSON. Path '', line 3, position 2.",
() => () =>
{ {
string json = @"{ string json = @"{
@@ -1301,17 +1304,18 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, 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."
#endif
)]
public void DeserializeInterfaceProperty() public void DeserializeInterfaceProperty()
{ {
InterfacePropertyTestClass testClass = new InterfacePropertyTestClass(); InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
testClass.co = new Co(); testClass.co = new Co();
String strFromTest = JsonConvert.SerializeObject(testClass); String strFromTest = JsonConvert.SerializeObject(testClass);
ExceptionAssert.Throws<JsonSerializationException>(
@"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Path 'co.Name', line 1, position 14.",
() =>
{
InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass) JsonConvert.DeserializeObject(strFromTest, typeof (InterfacePropertyTestClass)); InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass) JsonConvert.DeserializeObject(strFromTest, typeof (InterfacePropertyTestClass));
});
} }
private Person GetPerson() private Person GetPerson()
@@ -1471,13 +1475,19 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException))]
public void JsonPropertyWithHandlingValues_ReferenceLoopError() public void JsonPropertyWithHandlingValues_ReferenceLoopError()
{
string classRef = typeof(JsonPropertyWithHandlingValues).FullName;
ExceptionAssert.Throws<JsonSerializationException>(
@"Self referencing loop detected for type '" + classRef + "'.",
() =>
{ {
JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues(); JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues();
o.ReferenceLoopHandlingErrorProperty = o; o.ReferenceLoopHandlingErrorProperty = o;
JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}); JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
});
} }
[Test] [Test]
@@ -1957,16 +1967,16 @@ keyword such as type of business.""
#endif #endif
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, 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."
#endif
)]
public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments() 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)\/""}"; 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)\/""}";
ExceptionAssert.Throws<JsonSerializationException>(
@"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. Path 'sublocation', line 1, position 15.",
() =>
{
Event e = JsonConvert.DeserializeObject<Event>(json); Event e = JsonConvert.DeserializeObject<Event>(json);
});
} }
[Test] [Test]
@@ -2001,59 +2011,59 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.
To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line 1, position 1."
#endif
)]
public void CannotDeserializeArrayIntoObject() public void CannotDeserializeArrayIntoObject()
{ {
string json = @"[]"; string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.
To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Path '', line 1, position 1.",
() =>
{
JsonConvert.DeserializeObject<Person>(json); JsonConvert.DeserializeObject<Person>(json);
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.
The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List<T>) or a dictionary type (i.e. Dictionary<TKey, TValue>).
To force JSON objects to deserialize add the JsonObjectAttribute to the type. Line 1, position 2."
#endif
)]
public void CannotDeserializeObjectIntoArray() public void CannotDeserializeObjectIntoArray()
{ {
string json = @"{}"; string json = @"{}";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'.
The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List<T>) or a dictionary type (i.e. Dictionary<TKey, TValue>).
To force JSON objects to deserialize add the JsonObjectAttribute to the type. Path '', line 1, position 2.",
() =>
{
JsonConvert.DeserializeObject<List<Person>>(json); JsonConvert.DeserializeObject<List<Person>>(json);
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1."
#endif
)]
public void CannotPopulateArrayIntoObject() public void CannotPopulateArrayIntoObject()
{ {
string json = @"[]"; string json = @"[]";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.",
() =>
{
JsonConvert.PopulateObject(json, new Person()); JsonConvert.PopulateObject(json, new Person());
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2."
#endif
)]
public void CannotPopulateObjectIntoArray() public void CannotPopulateObjectIntoArray()
{ {
string json = @"{}"; string json = @"{}";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.",
() =>
{
JsonConvert.PopulateObject(json, new List<Person>()); JsonConvert.PopulateObject(json, new List<Person>());
});
} }
[Test] [Test]
@@ -2066,12 +2076,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'."
#endif
)]
public void SerializePropertyGetError() public void SerializePropertyGetError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",
() =>
{ {
JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings
{ {
@@ -2082,15 +2091,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
#endif #endif
} }
}); });
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'."
#endif
)]
public void DeserializePropertySetError() public void DeserializePropertySetError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.",
() =>
{ {
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:0}", new JsonSerializerSettings
{ {
@@ -2101,15 +2110,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
#endif #endif
} }
}); });
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonReaderException)
#if !NETFX_CORE
, ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15."
#endif
)]
public void DeserializeEnsureTypeEmptyStringToIntError() public void DeserializeEnsureTypeEmptyStringToIntError()
{
ExceptionAssert.Throws<JsonReaderException>(
@"Could not convert string to integer: . Path 'ReadTimeout', line 1, position 15.",
() =>
{ {
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
{ {
@@ -2120,15 +2129,15 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
#endif #endif
} }
}); });
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17."
#endif
)]
public void DeserializeEnsureTypeNullToIntError() public void DeserializeEnsureTypeNullToIntError()
{
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.",
() =>
{ {
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}", new JsonSerializerSettings
{ {
@@ -2139,6 +2148,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
#endif #endif
} }
}); });
});
} }
[Test] [Test]
@@ -2252,7 +2262,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
[Test] [Test]
public void DeserializePersonKeyedDictionary() public void DeserializePersonKeyedDictionary()
{ {
ExceptionAssert.Throws<JsonSerializationException>("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.", ExceptionAssert.Throws<JsonSerializationException>("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. Path 'Newtonsoft.Json.Tests.TestObjects.Person', line 2, position 46.",
() => () =>
{ {
string json = string json =
@@ -2518,15 +2528,16 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6."
#endif
)]
public void DeserializeDictionaryWithNoDefaultConstructor() public void DeserializeDictionaryWithNoDefaultConstructor()
{ {
string json = "{key1:'value',key2:'value',key3:'value'}"; string json = "{key1:'value',key2:'value',key3:'value'}";
ExceptionAssert.Throws<JsonSerializationException>(
"Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 6.",
() =>
{
JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json); JsonConvert.DeserializeObject<DictionaryWithNoDefaultConstructor>(json);
});
} }
public class DictionaryWithNoDefaultConstructor : Dictionary<string, string> public class DictionaryWithNoDefaultConstructor : Dictionary<string, string>
@@ -2913,7 +2924,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li
{ {
ExceptionAssert.Throws<JsonSerializationException>( ExceptionAssert.Throws<JsonSerializationException>(
@"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data. @"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Line 1, position 14.", To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Path 'booleanValue', line 1, position 14.",
() => () =>
{ {
JsonTypeReflector.SetFullyTrusted(false); JsonTypeReflector.SetFullyTrusted(false);
@@ -3608,11 +3619,6 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11."
#endif
)]
public void SerializeRefAdditionalContent() public void SerializeRefAdditionalContent()
{ {
//Additional text found in JSON string after finishing deserializing object. //Additional text found in JSON string after finishing deserializing object.
@@ -3627,13 +3633,20 @@ To fix this error either change the environment to be fully trusted, change the
child.Add("Father", reference); child.Add("Father", reference);
var json = JsonConvert.SerializeObject(child, Formatting.Indented); var json = JsonConvert.SerializeObject(child, Formatting.Indented);
ExceptionAssert.Throws<JsonSerializationException>(
"Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.",
() =>
{
JsonConvert.DeserializeObject<Dictionary<string, object>>(json); JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
});
} }
[Test] [Test]
public void SerializeRefBadType() public void SerializeRefBadType()
{ {
ExceptionAssert.Throws<JsonSerializationException>("JSON reference $ref property must have a string or null value. Line 5, position 14.", ExceptionAssert.Throws<JsonSerializationException>(
"JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.",
() => () =>
{ {
//Additional text found in JSON string after finishing deserializing object. //Additional text found in JSON string after finishing deserializing object.
@@ -4071,9 +4084,10 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (Exception), ExpectedMessage = "Cannot create and populate list type System.Collections.Specialized.StringDictionary.")]
public void StringDictionaryTest() public void StringDictionaryTest()
{ {
string classRef = typeof(StringDictionary).FullName;
StringDictionaryTestClass s1 = new StringDictionaryTestClass() StringDictionaryTestClass s1 = new StringDictionaryTestClass()
{ {
StringDictionaryProperty = new StringDictionary() StringDictionaryProperty = new StringDictionary()
@@ -4086,7 +4100,12 @@ To fix this error either change the environment to be fully trusted, change the
string json = JsonConvert.SerializeObject(s1, Formatting.Indented); string json = JsonConvert.SerializeObject(s1, Formatting.Indented);
ExceptionAssert.Throws<InvalidOperationException>(
"Cannot create and populate list type " + classRef + ".",
() =>
{
JsonConvert.DeserializeObject<StringDictionaryTestClass>(json); JsonConvert.DeserializeObject<StringDictionaryTestClass>(json);
});
} }
#endif #endif
@@ -4649,14 +4668,14 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4."
#endif
)]
public void DeserializeNullDateTimeValueTest() public void DeserializeNullDateTimeValueTest()
{
ExceptionAssert.Throws<JsonSerializationException>(
"Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.",
() =>
{ {
JsonConvert.DeserializeObject("null", typeof (DateTime)); JsonConvert.DeserializeObject("null", typeof (DateTime));
});
} }
[Test] [Test]
@@ -5360,16 +5379,16 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (Exception)
#if !NETFX_CORE
, ExpectedMessage = "Could not deserialize Null to KeyValuePair."
#endif
)]
public void DeserializeNullToNonNullableKeyValuePairArray() public void DeserializeNullToNonNullableKeyValuePairArray()
{ {
string json = @"[ null ]"; string json = @"[ null ]";
ExceptionAssert.Throws<JsonSerializationException>(
"Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.",
() =>
{
JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json); JsonConvert.DeserializeObject<IList<KeyValuePair<string, IList<string>>>>(json);
});
} }
[Test] [Test]
@@ -5508,11 +5527,6 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7."
#endif
)]
public void DeserializeNullInt() public void DeserializeNullInt()
{ {
string json = @"[ string json = @"[
@@ -5522,8 +5536,12 @@ To fix this error either change the environment to be fully trusted, change the
null null
]"; ]";
ExceptionAssert.Throws<JsonSerializationException>(
"Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.",
() =>
{
List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json); List<int> numbers = JsonConvert.DeserializeObject<List<int>>(json);
// JsonSerializationException : Error converting value {null} to type 'System.Int32'. Line 5, position 7. });
} }
[Test] [Test]
@@ -5551,7 +5569,8 @@ To fix this error either change the environment to be fully trusted, change the
[Test] [Test]
public void DeserializeBoolInt() public void DeserializeBoolInt()
{ {
ExceptionAssert.Throws<JsonReaderException>("Error reading integer. Unexpected token: Boolean. Line 2, position 22.", ExceptionAssert.Throws<JsonReaderException>(
"Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.",
() => () =>
{ {
string json = @"{ string json = @"{
@@ -5566,7 +5585,8 @@ To fix this error either change the environment to be fully trusted, change the
[Test] [Test]
public void DeserializeUnexpectedEndInt() public void DeserializeUnexpectedEndInt()
{ {
ExceptionAssert.Throws<JsonSerializationException>("Unexpected end when setting PreProperty's value. Line 2, position 18.", ExceptionAssert.Throws<JsonSerializationException>(
"Unexpected end when setting PreProperty's value. Path 'PreProperty', line 2, position 18.",
() => () =>
{ {
string json = @"{ string json = @"{
@@ -5718,36 +5738,36 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "No JSON content found and type 'System.Double' is not nullable. Line 0, position 0."
#endif
)]
public void DeserializeDoubleFromEmptyString() public void DeserializeDoubleFromEmptyString()
{
ExceptionAssert.Throws<JsonSerializationException>(
"No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.",
() =>
{ {
JsonConvert.DeserializeObject<double>(""); JsonConvert.DeserializeObject<double>("");
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "No JSON content found and type 'System.StringComparison' is not nullable. Line 0, position 0."
#endif
)]
public void DeserializeEnumFromEmptyString() public void DeserializeEnumFromEmptyString()
{
ExceptionAssert.Throws<JsonSerializationException>(
"No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.",
() =>
{ {
JsonConvert.DeserializeObject<StringComparison>(""); JsonConvert.DeserializeObject<StringComparison>("");
});
} }
[Test] [Test]
[ExpectedException(typeof (JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "No JSON content found and type 'System.Int32' is not nullable. Line 0, position 0."
#endif
)]
public void DeserializeInt32FromEmptyString() public void DeserializeInt32FromEmptyString()
{
ExceptionAssert.Throws<JsonSerializationException>(
"No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.",
() =>
{ {
JsonConvert.DeserializeObject<int>(""); JsonConvert.DeserializeObject<int>("");
});
} }
[Test] [Test]
@@ -5758,27 +5778,28 @@ To fix this error either change the environment to be fully trusted, change the
} }
[Test] [Test]
[ExpectedException(typeof (ArgumentNullException)
#if !NETFX_CORE
, ExpectedMessage = @"Value cannot be null.
Parameter name: value"
#endif
)]
public void DeserializeDoubleFromNullString() public void DeserializeDoubleFromNullString()
{
ExceptionAssert.Throws<ArgumentNullException>(
@"Value cannot be null.
Parameter name: value",
() =>
{ {
JsonConvert.DeserializeObject<double>(null); JsonConvert.DeserializeObject<double>(null);
});
} }
[Test] [Test]
[ExpectedException(typeof (ArgumentNullException)
#if !NETFX_CORE
, ExpectedMessage = @"Value cannot be null.
Parameter name: value"
#endif
)]
public void DeserializeFromNullString() public void DeserializeFromNullString()
{
ExceptionAssert.Throws<ArgumentNullException>(
@"Value cannot be null.
Parameter name: value",
() =>
{ {
JsonConvert.DeserializeObject(null); JsonConvert.DeserializeObject(null);
});
} }
[Test] [Test]
@@ -41,11 +41,6 @@ namespace Newtonsoft.Json.Tests.Serialization
public class MissingMemberHandlingTests : TestFixtureBase public class MissingMemberHandlingTests : TestFixtureBase
{ {
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11."
#endif
)]
public void MissingMemberDeserialize() public void MissingMemberDeserialize()
{ {
Product product = new Product(); Product product = new Product();
@@ -67,7 +62,12 @@ namespace Newtonsoft.Json.Tests.Serialization
// ] // ]
//} //}
ExceptionAssert.Throws<JsonSerializationException>(
@"Could not find member 'Price' on object of type 'ProductShort'. Path 'Price', line 4, position 11.",
() =>
{
ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error });
});
} }
[Test] [Test]
@@ -126,16 +126,16 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11."
#endif
)]
public void MissingMemeber() public void MissingMemeber()
{ {
string json = @"{""Missing"":1}"; string json = @"{""Missing"":1}";
ExceptionAssert.Throws<JsonSerializationException>(
"Could not find member 'Missing' on object of type 'DoubleClass'. Path 'Missing', line 1, position 11.",
() =>
{
JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); JsonConvert.DeserializeObject<DoubleClass>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error });
});
} }
[Test] [Test]
@@ -140,7 +140,7 @@ namespace Newtonsoft.Json.Tests.Serialization
[Test] [Test]
public void PopulateWithBadJson() public void PopulateWithBadJson()
{ {
ExceptionAssert.Throws<JsonSerializationException>("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.", ExceptionAssert.Throws<JsonSerializationException>("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Path '', line 1, position 1.",
() => () =>
{ {
JsonConvert.PopulateObject("1", new Person()); JsonConvert.PopulateObject("1", new Person());
@@ -94,15 +94,21 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException))]
public void SerializeCircularListsError() public void SerializeCircularListsError()
{ {
string classRef = typeof(CircularList).FullName;
CircularList circularList = new CircularList(); CircularList circularList = new CircularList();
circularList.Add(null); circularList.Add(null);
circularList.Add(new CircularList { null }); circularList.Add(new CircularList { null });
circularList.Add(new CircularList { new CircularList { circularList } }); circularList.Add(new CircularList { new CircularList { circularList } });
ExceptionAssert.Throws<JsonSerializationException>(
"Self referencing loop detected for type '" + classRef + "'.",
() =>
{
JsonConvert.SerializeObject(circularList, Formatting.Indented); JsonConvert.SerializeObject(circularList, Formatting.Indented);
});
} }
[Test] [Test]
@@ -207,11 +213,6 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]. Line 3, position 15."
#endif
)]
public void DeserializeArraysWithPreserveObjectReferences() public void DeserializeArraysWithPreserveObjectReferences()
{ {
string json = @"{ string json = @"{
@@ -240,8 +241,13 @@ namespace Newtonsoft.Json.Tests.Serialization
] ]
}"; }";
ExceptionAssert.Throws<JsonSerializationException>(
@"Cannot preserve reference to array or readonly list: System.String[][]. Path '$values', line 3, position 15.",
() =>
{
JsonConvert.DeserializeObject<string[][]>(json, JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
});
} }
public class CircularDictionary : Dictionary<string, CircularDictionary> public class CircularDictionary : Dictionary<string, CircularDictionary>
@@ -249,14 +255,20 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException))]
public void SerializeCircularDictionarysError() public void SerializeCircularDictionarysError()
{ {
string classRef = typeof(CircularDictionary).FullName;
CircularDictionary circularDictionary = new CircularDictionary(); CircularDictionary circularDictionary = new CircularDictionary();
circularDictionary.Add("other", new CircularDictionary { { "blah", null } }); circularDictionary.Add("other", new CircularDictionary {{"blah", null}});
circularDictionary.Add("self", circularDictionary); circularDictionary.Add("self", circularDictionary);
ExceptionAssert.Throws<JsonSerializationException>(
@"Self referencing loop detected for type '" + classRef + "'.",
() =>
{
JsonConvert.SerializeObject(circularDictionary, Formatting.Indented); JsonConvert.SerializeObject(circularDictionary, Formatting.Indented);
});
} }
[Test] [Test]
@@ -277,18 +289,18 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = @"Unexpected end when deserializing object. Line 2, position 9."
#endif
)]
public void UnexpectedEnd() public void UnexpectedEnd()
{ {
string json = @"{ string json = @"{
""$id"":"; ""$id"":";
ExceptionAssert.Throws<JsonSerializationException>(
@"Unexpected end when deserializing object. Path '$id', line 2, position 9.",
() =>
{
JsonConvert.DeserializeObject<string[][]>(json, JsonConvert.DeserializeObject<string[][]>(json,
new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All });
});
} }
public class CircularReferenceClassConverter : JsonConverter public class CircularReferenceClassConverter : JsonConverter
@@ -205,8 +205,8 @@ namespace Newtonsoft.Json.Tests.Serialization
#else #else
Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]); Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]);
#endif #endif
Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray.", errors[1]); Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray. Path '[2]', line 4, position 10.", errors[1]);
Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime.", errors[2]); Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime. Path '[4]', line 8, position 13.", errors[2]);
} }
[Test] [Test]
@@ -294,10 +294,10 @@ namespace Newtonsoft.Json.Tests.Serialization
e = ex; e = ex;
} }
Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", e.Message); Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Path '[0][0]', line 1, position 16.", e.Message);
Assert.AreEqual(1, errors.Count); Assert.AreEqual(1, errors.Count);
Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", errors[0]); Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Path '[0][0]', line 1, position 16.", errors[0]);
} }
[Test] [Test]
@@ -314,8 +314,8 @@ namespace Newtonsoft.Json.Tests.Serialization
serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof (MyTypeWithRequiredMembers)); serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof (MyTypeWithRequiredMembers));
Assert.AreEqual(2, errors.Count); Assert.AreEqual(2, errors.Count);
Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Line 1, position 2.", errors[0]); Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Path '', line 1, position 2.", errors[0]);
Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Line 1, position 2.", errors[1]); Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Path '', line 1, position 2.", errors[1]);
} }
[Test] [Test]
@@ -335,8 +335,8 @@ namespace Newtonsoft.Json.Tests.Serialization
serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof(int[])); serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof(int[]));
Assert.AreEqual(2, errors.Count); Assert.AreEqual(2, errors.Count);
Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Line 1, position 4.", errors[0]); Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Path '[0]', line 1, position 4.", errors[0]);
Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Line 1, position 8.", errors[1]); Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Path '[1]', line 1, position 8.", errors[1]);
} }
[Test] [Test]
@@ -262,10 +262,10 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException))]
public void DeserializeWithBadTypeName() public void DeserializeWithBadTypeName()
{ {
string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName; string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName;
string personRef = typeof(Person).AssemblyQualifiedName;
string json = @"{ string json = @"{
""$id"": ""1"", ""$id"": ""1"",
@@ -274,11 +274,16 @@ namespace Newtonsoft.Json.Tests.Serialization
""Manager"": null ""Manager"": null
}"; }";
JsonConvert.DeserializeObject(json, typeof(Person), new JsonSerializerSettings ExceptionAssert.Throws<JsonSerializationException>(
@"Type specified in JSON '" + employeeRef + @"' is not compatible with '" + personRef + @"'. Path '$type', line 3, position 143.",
() =>
{
JsonConvert.DeserializeObject(json, typeof (Person), new JsonSerializerSettings
{ {
TypeNameHandling = TypeNameHandling.Objects, TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
}); });
});
} }
[Test] [Test]
@@ -302,11 +307,6 @@ namespace Newtonsoft.Json.Tests.Serialization
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException)
#if !NETFX_CORE
, ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Line 3, position 56."
#endif
)]
public void DeserializeTypeNameOnly() public void DeserializeTypeNameOnly()
{ {
string json = @"{ string json = @"{
@@ -316,10 +316,15 @@ namespace Newtonsoft.Json.Tests.Serialization
""Manager"": null ""Manager"": null
}"; }";
ExceptionAssert.Throws<JsonSerializationException>(
"Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.",
() =>
{
JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{ {
TypeNameHandling = TypeNameHandling.Objects TypeNameHandling = TypeNameHandling.Objects
}); });
});
} }
public interface ICorrelatedMessage public interface ICorrelatedMessage
+1 -1
View File
@@ -129,7 +129,7 @@ namespace Newtonsoft.Json.Tests
catch (TException ex) catch (TException ex)
{ {
if (message != null) if (message != null)
Assert.AreEqual(message, ex.Message); Assert.AreEqual(message, ex.Message, "Unexpected exception message." + Environment.NewLine + "Expected: " + message + Environment.NewLine + "Got: " + ex.Message);
} }
catch (Exception ex) catch (Exception ex)
{ {
+1 -1
View File
@@ -47,7 +47,7 @@ namespace Newtonsoft.Json.Bson
{ {
ValidationUtils.ArgumentNotNull(value, "value"); ValidationUtils.ArgumentNotNull(value, "value");
if (value.Length != 12) if (value.Length != 12)
throw new Exception("An ObjectId must be 12 bytes"); throw new ArgumentException("An ObjectId must be 12 bytes", "value");
Value = value; Value = value;
} }
+6 -6
View File
@@ -269,7 +269,7 @@ namespace Newtonsoft.Json.Bson
success = ReadCodeWScope(); success = ReadCodeWScope();
break; break;
default: default:
throw CreateReaderException(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState)); throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
} }
if (!success) if (!success)
@@ -373,7 +373,7 @@ namespace Newtonsoft.Json.Bson
} }
else else
{ {
throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
} }
} }
case State.PostValue: case State.PostValue:
@@ -392,11 +392,11 @@ namespace Newtonsoft.Json.Bson
} }
else else
{ {
throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
} }
} }
default: default:
throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + CurrentState); throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState);
} }
} }
@@ -449,7 +449,7 @@ namespace Newtonsoft.Json.Bson
else if (context.Position == lengthMinusEnd) else if (context.Position == lengthMinusEnd)
{ {
if (ReadByte() != 0) if (ReadByte() != 0)
throw CreateReaderException(this, "Unexpected end of object byte value."); throw JsonReaderException.Create(this, "Unexpected end of object byte value.");
PopContext(); PopContext();
if (_currentContext != null) if (_currentContext != null)
@@ -461,7 +461,7 @@ namespace Newtonsoft.Json.Bson
} }
else else
{ {
throw CreateReaderException(this, "Read past end of current container context."); throw JsonReaderException.Create(this, "Read past end of current container context.");
} }
case State.ConstructorStart: case State.ConstructorStart:
break; break;
+1 -1
View File
@@ -470,7 +470,7 @@ namespace Newtonsoft.Json.Bson
ValidationUtils.ArgumentNotNull(value, "value"); ValidationUtils.ArgumentNotNull(value, "value");
if (value.Length != 12) if (value.Length != 12)
throw new Exception("An object id must be 12 bytes"); throw new ArgumentException("An object id must be 12 bytes", "value");
// hack to update the writer state // hack to update the writer state
AutoComplete(JsonToken.Undefined); AutoComplete(JsonToken.Undefined);
@@ -79,7 +79,7 @@ namespace Newtonsoft.Json.Converters
if (value is SqlBinary) if (value is SqlBinary)
return ((SqlBinary) value).Value; return ((SqlBinary) value).Value;
throw new Exception("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType())); throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
} }
/// <summary> /// <summary>
@@ -99,7 +99,7 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Null) if (reader.TokenType == JsonToken.Null)
{ {
if (!ReflectionUtils.IsNullable(objectType)) if (!ReflectionUtils.IsNullable(objectType))
throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null; return null;
} }
@@ -119,7 +119,7 @@ namespace Newtonsoft.Json.Converters
} }
else else
{ {
throw new Exception("Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
@@ -131,7 +131,7 @@ namespace Newtonsoft.Json.Converters
if (t == typeof(SqlBinary)) if (t == typeof(SqlBinary))
return new SqlBinary(data); return new SqlBinary(data);
throw new Exception("Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
private byte[] ReadByteArray(JsonReader reader) private byte[] ReadByteArray(JsonReader reader)
@@ -151,11 +151,11 @@ namespace Newtonsoft.Json.Converters
// skip // skip
break; break;
default: default:
throw new Exception("Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
} }
throw new Exception("Unexpected end when reading bytes."); throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
} }
/// <summary> /// <summary>
@@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Converters
while (reader.TokenType == JsonToken.Comment) while (reader.TokenType == JsonToken.Comment)
{ {
if (!reader.Read()) if (!reader.Read())
throw new Exception("Unexpected end."); throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
} }
switch (reader.TokenType) switch (reader.TokenType)
@@ -57,7 +57,7 @@ namespace Newtonsoft.Json.Converters
if (JsonReader.IsPrimitiveToken(reader.TokenType)) if (JsonReader.IsPrimitiveToken(reader.TokenType))
return reader.Value; return reader.Value;
throw new Exception("Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
} }
@@ -81,7 +81,7 @@ namespace Newtonsoft.Json.Converters
} }
} }
throw new Exception("Unexpected end."); throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
} }
private object ReadObject(JsonReader reader) private object ReadObject(JsonReader reader)
@@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Converters
string propertyName = reader.Value.ToString(); string propertyName = reader.Value.ToString();
if (!reader.Read()) if (!reader.Read())
throw new Exception("Unexpected end."); throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
object v = ReadValue(reader); object v = ReadValue(reader);
@@ -109,7 +109,7 @@ namespace Newtonsoft.Json.Converters
} }
} }
throw new Exception("Unexpected end."); throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
} }
/// <summary> /// <summary>
@@ -78,7 +78,7 @@ namespace Newtonsoft.Json.Converters
#endif #endif
else else
{ {
throw new Exception("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value))); throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
} }
writer.WriteValue(text); writer.WriteValue(text);
@@ -102,7 +102,7 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Null) if (reader.TokenType == JsonToken.Null)
{ {
if (!ReflectionUtils.IsNullableType(objectType)) if (!ReflectionUtils.IsNullableType(objectType))
throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null; return null;
} }
@@ -118,7 +118,7 @@ namespace Newtonsoft.Json.Converters
} }
if (reader.TokenType != JsonToken.String) if (reader.TokenType != JsonToken.String)
throw new Exception("Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
string dateText = reader.Value.ToString(); string dateText = reader.Value.ToString();
@@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Converters
#endif #endif
else else
{ {
throw new Exception("Expected date object value."); throw new JsonSerializationException("Expected date object value.");
} }
writer.WriteStartConstructor("Date"); writer.WriteStartConstructor("Date");
@@ -60,18 +60,18 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Null) if (reader.TokenType == JsonToken.Null)
{ {
if (!ReflectionUtils.IsNullableType(objectType)) if (!ReflectionUtils.IsNullableType(objectType))
throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null; return null;
} }
if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
throw new Exception("Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
reader.Read(); reader.Read();
if (reader.TokenType != JsonToken.Integer) if (reader.TokenType != JsonToken.Integer)
throw new Exception("Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
long ticks = (long)reader.Value; long ticks = (long)reader.Value;
@@ -80,7 +80,7 @@ namespace Newtonsoft.Json.Converters
reader.Read(); reader.Read();
if (reader.TokenType != JsonToken.EndConstructor) if (reader.TokenType != JsonToken.EndConstructor)
throw new Exception("Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
#if !PocketPC && !NET20 #if !PocketPC && !NET20
if (t == typeof(DateTimeOffset)) if (t == typeof(DateTimeOffset))
@@ -45,7 +45,7 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Null) if (reader.TokenType == JsonToken.Null)
{ {
if (!isNullable) if (!isNullable)
throw new Exception("Could not deserialize Null to KeyValuePair."); throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
return null; return null;
} }
@@ -110,7 +110,7 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Null) if (reader.TokenType == JsonToken.Null)
{ {
if (!ReflectionUtils.IsNullableType(objectType)) if (!ReflectionUtils.IsNullableType(objectType))
throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
return null; return null;
} }
@@ -128,7 +128,7 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Integer) if (reader.TokenType == JsonToken.Integer)
return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t); return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
throw new Exception("Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
/// <summary> /// <summary>
@@ -168,7 +168,7 @@ namespace Newtonsoft.Json.Converters
string s; string s;
if (map.TryGetBySecond(n2, out s)) if (map.TryGetBySecond(n2, out s))
{ {
throw new Exception("Enum name '{0}' already exists on enum '{1}'." throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'."
.FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); .FormatWith(CultureInfo.InvariantCulture, n2, t.Name));
} }
@@ -52,7 +52,7 @@ namespace Newtonsoft.Json.Converters
} }
else else
{ {
throw new Exception("Expected Version object value"); throw new JsonSerializationException("Expected Version object value");
} }
} }
@@ -81,12 +81,12 @@ namespace Newtonsoft.Json.Converters
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new Exception("Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex); throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
} }
} }
else else
{ {
throw new Exception("Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
} }
} }
} }
@@ -1274,7 +1274,7 @@ namespace Newtonsoft.Json.Converters
} }
else else
{ {
throw new Exception("Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
} }
+58
View File
@@ -35,6 +35,14 @@ namespace Newtonsoft.Json
{ {
private bool _allowNullItems; private bool _allowNullItems;
// yuck. can't set nullable properties on an attribute in C#
// have to use this approach to get an unset default state
internal NullValueHandling? _itemNullValueHandling;
internal DefaultValueHandling? _itemDefaultValueHandling;
internal ReferenceLoopHandling? _itemReferenceLoopHandling;
internal ObjectCreationHandling? _itemObjectCreationHandling;
internal TypeNameHandling? _itemTypeNameHandling;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether null items are allowed in the collection. /// Gets or sets a value indicating whether null items are allowed in the collection.
/// </summary> /// </summary>
@@ -45,6 +53,56 @@ namespace Newtonsoft.Json
set { _allowNullItems = value; } set { _allowNullItems = value; }
} }
/// <summary>
/// Gets or sets the null value handling used when serializing the collection's items.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling ItemNullValueHandling
{
get { return _itemNullValueHandling ?? default(NullValueHandling); }
set { _itemNullValueHandling = value; }
}
/// <summary>
/// Gets or sets the default value handling used when serializing the collection's items.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling ItemDefaultValueHandling
{
get { return _itemDefaultValueHandling ?? default(DefaultValueHandling); }
set { _itemDefaultValueHandling = value; }
}
/// <summary>
/// Gets or sets the reference loop handling used when serializing the collection's items.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling ItemReferenceLoopHandling
{
get { return _itemReferenceLoopHandling ?? default(ReferenceLoopHandling); }
set { _itemReferenceLoopHandling = value; }
}
/// <summary>
/// Gets or sets the object creation handling used when deserializing the collection's items.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling ItemObjectCreationHandling
{
get { return _itemObjectCreationHandling ?? default(ObjectCreationHandling); }
set { _itemObjectCreationHandling = value; }
}
/// <summary>
/// Gets or sets the type name handling used when serializing the collection's items.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling ItemTypeNameHandling
{
get { return _itemTypeNameHandling ?? default(TypeNameHandling); }
set { _itemTypeNameHandling = value; }
}
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="JsonArrayAttribute"/> class. /// Initializes a new instance of the <see cref="JsonArrayAttribute"/> class.
/// </summary> /// </summary>
@@ -41,7 +41,7 @@ namespace Newtonsoft.Json
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new Exception("Error creating {0}".FormatWith(CultureInfo.InvariantCulture, converterType), ex); throw new JsonException("Error creating {0}".FormatWith(CultureInfo.InvariantCulture, converterType), ex);
} }
} }
} }
+83
View File
@@ -0,0 +1,83 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// The exception thrown when an error occurs during Json serialization or deserialization.
/// </summary>
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable]
#endif
public class JsonException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class.
/// </summary>
public JsonException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public JsonException(string message, Exception innerException)
: base(message, innerException)
{
}
#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE || PORTABLE)
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
public JsonException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
+18 -59
View File
@@ -273,7 +273,7 @@ namespace Newtonsoft.Json
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{ {
_hasExceededMaxDepth = true; _hasExceededMaxDepth = true;
throw CreateReaderException(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
} }
} }
} }
@@ -388,14 +388,14 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
} }
} }
if (TokenType == JsonToken.EndArray) if (TokenType == JsonToken.EndArray)
return null; return null;
throw CreateReaderException(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
#endif #endif
@@ -453,17 +453,17 @@ namespace Newtonsoft.Json
// skip // skip
break; break;
default: default:
throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
} }
throw CreateReaderException(this, "Unexpected end when reading bytes."); throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
} }
if (TokenType == JsonToken.EndArray) if (TokenType == JsonToken.EndArray)
return null; return null;
throw CreateReaderException(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
internal decimal? ReadAsDecimalInternal() internal decimal? ReadAsDecimalInternal()
@@ -500,14 +500,14 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
} }
} }
if (TokenType == JsonToken.EndArray) if (TokenType == JsonToken.EndArray)
return null; return null;
throw CreateReaderException(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
internal int? ReadAsInt32Internal() internal int? ReadAsInt32Internal()
@@ -544,14 +544,14 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
} }
} }
if (TokenType == JsonToken.EndArray) if (TokenType == JsonToken.EndArray)
return null; return null;
throw CreateReaderException(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
internal string ReadAsStringInternal() internal string ReadAsStringInternal()
@@ -593,7 +593,7 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.EndArray) if (TokenType == JsonToken.EndArray)
return null; return null;
throw CreateReaderException(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
internal DateTime? ReadAsDateTimeInternal() internal DateTime? ReadAsDateTimeInternal()
@@ -633,14 +633,14 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
} }
} }
if (TokenType == JsonToken.EndArray) if (TokenType == JsonToken.EndArray)
return null; return null;
throw CreateReaderException(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
private bool IsWrappedInTypeObject() private bool IsWrappedInTypeObject()
@@ -650,7 +650,7 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.StartObject) if (TokenType == JsonToken.StartObject)
{ {
if (!ReadInternal()) if (!ReadInternal())
throw CreateReaderException(this, "Unexpected end when reading bytes."); throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
if (Value.ToString() == "$type") if (Value.ToString() == "$type")
{ {
@@ -665,7 +665,7 @@ namespace Newtonsoft.Json
} }
} }
throw CreateReaderException(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
} }
return false; return false;
@@ -771,7 +771,7 @@ namespace Newtonsoft.Json
JsonContainerType currentObject = Pop(); JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject) if (GetTypeForCloseToken(endToken) != currentObject)
throw CreateReaderException(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
_currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished; _currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished;
} }
@@ -798,7 +798,7 @@ namespace Newtonsoft.Json
_currentState = State.Finished; _currentState = State.Finished;
break; break;
default: default:
throw CreateReaderException(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
} }
} }
@@ -844,7 +844,7 @@ namespace Newtonsoft.Json
case JsonToken.EndConstructor: case JsonToken.EndConstructor:
return JsonContainerType.Constructor; return JsonContainerType.Constructor;
default: default:
throw CreateReaderException(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
} }
} }
@@ -875,46 +875,5 @@ namespace Newtonsoft.Json
_tokenType = JsonToken.None; _tokenType = JsonToken.None;
_value = null; _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 && lineInfo.HasLineInfo())
{
lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition;
}
else
{
lineNumber = 0;
linePosition = 0;
}
return new JsonReaderException(message, ex, Path, lineNumber, linePosition);
}
internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string message)
{
if (!message.EndsWith("."))
message += ".";
if (lineInfo != null && lineInfo.HasLineInfo())
message += " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
return message;
}
} }
} }
+50 -1
View File
@@ -24,7 +24,9 @@
#endregion #endregion
using System; using System;
using System.Globalization;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json namespace Newtonsoft.Json
{ {
@@ -34,7 +36,7 @@ namespace Newtonsoft.Json
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable] [Serializable]
#endif #endif
public class JsonReaderException : Exception public class JsonReaderException : JsonException
{ {
/// <summary> /// <summary>
/// Gets the line number indicating where the error occurred. /// Gets the line number indicating where the error occurred.
@@ -104,5 +106,52 @@ namespace Newtonsoft.Json
LineNumber = lineNumber; LineNumber = lineNumber;
LinePosition = linePosition; LinePosition = linePosition;
} }
internal static JsonReaderException Create(JsonReader reader, string message)
{
return Create(reader, message, null);
}
internal static JsonReaderException Create(JsonReader reader, string message, Exception ex)
{
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
message = FormatExceptionMessage(lineInfo, path, message);
int lineNumber;
int linePosition;
if (lineInfo != null && lineInfo.HasLineInfo())
{
lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition;
}
else
{
lineNumber = 0;
linePosition = 0;
}
return new JsonReaderException(message, ex, path, lineNumber, linePosition);
}
internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string path, string message)
{
message = message.Trim();
if (!message.EndsWith("."))
message += ".";
message += " Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
if (lineInfo != null && lineInfo.HasLineInfo())
message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
message += ".";
return message;
}
} }
} }
@@ -36,7 +36,7 @@ namespace Newtonsoft.Json
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable] [Serializable]
#endif #endif
public class JsonSerializationException : Exception public class JsonSerializationException : JsonException
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class. /// Initializes a new instance of the <see cref="JsonSerializationException"/> class.
@@ -79,5 +79,22 @@ namespace Newtonsoft.Json
{ {
} }
#endif #endif
internal static JsonSerializationException Create(JsonReader reader, string message)
{
return Create(reader, message, null);
}
internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex)
{
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
{
message = JsonReaderException.FormatExceptionMessage(lineInfo, path, message);
return new JsonSerializationException(message, ex);
}
} }
} }
+27 -27
View File
@@ -501,7 +501,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
} }
} }
return false; return false;
@@ -510,7 +510,7 @@ namespace Newtonsoft.Json
case State.Error: case State.Error:
break; break;
default: default:
throw CreateReaderException(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
} }
} }
} }
@@ -534,7 +534,7 @@ namespace Newtonsoft.Json
if (ReadData(true) == 0) if (ReadData(true) == 0)
{ {
_charPos = charPos; _charPos = charPos;
throw CreateReaderException(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
} }
} }
break; break;
@@ -543,7 +543,7 @@ namespace Newtonsoft.Json
if (!EnsureChars(0, true)) if (!EnsureChars(0, true))
{ {
_charPos = charPos; _charPos = charPos;
throw CreateReaderException(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
} }
// start of escape sequence // start of escape sequence
@@ -648,7 +648,7 @@ namespace Newtonsoft.Json
default: default:
charPos++; charPos++;
_charPos = charPos; _charPos = charPos;
throw CreateReaderException(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
} }
if (buffer == null) if (buffer == null)
@@ -721,7 +721,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Unexpected end while parsing unicode character."); throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character.");
} }
return writeChar; return writeChar;
} }
@@ -848,7 +848,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
} }
break; break;
} }
@@ -927,7 +927,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
} }
string propertyName = _stringReference.ToString(); string propertyName = _stringReference.ToString();
@@ -935,7 +935,7 @@ namespace Newtonsoft.Json
EatWhitespace(false); EatWhitespace(false);
if (_chars[_charPos] != ':') if (_chars[_charPos] != ':')
throw CreateReaderException(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++; _charPos++;
@@ -964,7 +964,7 @@ namespace Newtonsoft.Json
if (_charsUsed == _charPos) if (_charsUsed == _charPos)
{ {
if (ReadData(true) == 0) if (ReadData(true) == 0)
throw CreateReaderException(this, "Unexpected end while parsing unquoted property name."); throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
break; break;
} }
@@ -985,7 +985,7 @@ namespace Newtonsoft.Json
return; return;
} }
throw CreateReaderException(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
} }
} }
} }
@@ -1029,11 +1029,11 @@ namespace Newtonsoft.Json
else if (next == 'e') else if (next == 'e')
ParseConstructor(); ParseConstructor();
else else
throw CreateReaderException(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
} }
else else
{ {
throw CreateReaderException(this, "Unexpected end."); throw JsonReaderException.Create(this, "Unexpected end.");
} }
return true; return true;
case 'N': case 'N':
@@ -1100,7 +1100,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
} }
} }
} }
@@ -1183,7 +1183,7 @@ namespace Newtonsoft.Json
if (_charsUsed == _charPos) if (_charsUsed == _charPos)
{ {
if (ReadData(true) == 0) if (ReadData(true) == 0)
throw CreateReaderException(this, "Unexpected end while parsing constructor."); throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
} }
else else
{ {
@@ -1221,7 +1221,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
} }
} }
@@ -1231,7 +1231,7 @@ namespace Newtonsoft.Json
EatWhitespace(false); EatWhitespace(false);
if (_chars[_charPos] != '(') if (_chars[_charPos] != '(')
throw CreateReaderException(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
_charPos++; _charPos++;
@@ -1350,7 +1350,7 @@ namespace Newtonsoft.Json
} }
catch (OverflowException ex) catch (OverflowException ex)
{ {
throw CreateReaderException((JsonReader)this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex); throw JsonReaderException.Create((JsonReader)this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex);
} }
numberType = JsonToken.Integer; numberType = JsonToken.Integer;
@@ -1369,7 +1369,7 @@ namespace Newtonsoft.Json
_charPos++; _charPos++;
if (!EnsureChars(1, false) || _chars[_charPos] != '*') if (!EnsureChars(1, false) || _chars[_charPos] != '*')
throw CreateReaderException(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
else else
_charPos++; _charPos++;
@@ -1385,7 +1385,7 @@ namespace Newtonsoft.Json
if (_charsUsed == _charPos) if (_charsUsed == _charPos)
{ {
if (ReadData(true) == 0) if (ReadData(true) == 0)
throw CreateReaderException(this, "Unexpected end while parsing comment."); throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
} }
else else
{ {
@@ -1498,7 +1498,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing boolean value."); throw JsonReaderException.Create(this, "Error parsing boolean value.");
} }
} }
@@ -1510,7 +1510,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing null value."); throw JsonReaderException.Create(this, "Error parsing null value.");
} }
} }
@@ -1522,7 +1522,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing undefined value."); throw JsonReaderException.Create(this, "Error parsing undefined value.");
} }
} }
@@ -1534,7 +1534,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing boolean value."); throw JsonReaderException.Create(this, "Error parsing boolean value.");
} }
} }
@@ -1546,7 +1546,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing negative infinity value."); throw JsonReaderException.Create(this, "Error parsing negative infinity value.");
} }
} }
@@ -1558,7 +1558,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing positive infinity value."); throw JsonReaderException.Create(this, "Error parsing positive infinity value.");
} }
} }
@@ -1570,7 +1570,7 @@ namespace Newtonsoft.Json
} }
else else
{ {
throw CreateReaderException(this, "Error parsing NaN value."); throw JsonReaderException.Create(this, "Error parsing NaN value.");
} }
} }
+2 -2
View File
@@ -188,7 +188,7 @@ namespace Newtonsoft.Json
case JTokenType.Object: case JTokenType.Object:
{ {
if (_currentScope.CurrentPropertyName == null) if (_currentScope.CurrentPropertyName == null)
throw new Exception("CurrentPropertyName has not been set on scope."); throw new JsonReaderException("CurrentPropertyName has not been set on scope.");
IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>(); IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>();
@@ -291,7 +291,7 @@ namespace Newtonsoft.Json
set set
{ {
if (TokenType != JsonToken.None) if (TokenType != JsonToken.None)
throw new Exception("Cannot change schema while validating JSON."); throw new InvalidOperationException("Cannot change schema while validating JSON.");
_schema = value; _schema = value;
_model = null; _model = null;
+1 -1
View File
@@ -36,7 +36,7 @@ namespace Newtonsoft.Json
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable] [Serializable]
#endif #endif
public class JsonWriterException : Exception public class JsonWriterException : JsonException
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class. /// Initializes a new instance of the <see cref="JsonWriterException"/> class.
+6 -6
View File
@@ -111,10 +111,10 @@ namespace Newtonsoft.Json.Linq
if (reader.TokenType == JsonToken.None) if (reader.TokenType == JsonToken.None)
{ {
if (!reader.Read()) if (!reader.Read())
throw new Exception("Error reading JArray from JsonReader."); throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader.");
} }
if (reader.TokenType != JsonToken.StartArray) if (reader.TokenType != JsonToken.StartArray)
throw new Exception("Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); 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(); JArray a = new JArray();
a.SetLineInfo(reader as IJsonLineInfo); a.SetLineInfo(reader as IJsonLineInfo);
@@ -131,12 +131,12 @@ namespace Newtonsoft.Json.Linq
/// <returns>A <see cref="JArray"/> populated from the string that contains JSON.</returns> /// <returns>A <see cref="JArray"/> populated from the string that contains JSON.</returns>
public static new JArray Parse(string json) public static new JArray Parse(string json)
{ {
JsonReader jsonReader = new JsonTextReader(new StringReader(json)); JsonReader reader = new JsonTextReader(new StringReader(json));
JArray a = Load(jsonReader); JArray a = Load(reader);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) if (reader.Read() && reader.TokenType != JsonToken.Comment)
throw new Exception("Additional text found in JSON string after parsing content."); throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
return a; return a;
} }
+2 -2
View File
@@ -184,11 +184,11 @@ namespace Newtonsoft.Json.Linq
if (reader.TokenType == JsonToken.None) if (reader.TokenType == JsonToken.None)
{ {
if (!reader.Read()) if (!reader.Read())
throw new Exception("Error reading JConstructor from JsonReader."); throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader.");
} }
if (reader.TokenType != JsonToken.StartConstructor) if (reader.TokenType != JsonToken.StartConstructor)
throw new Exception("Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); 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); JConstructor c = new JConstructor((string)reader.Value);
c.SetLineInfo(reader as IJsonLineInfo); c.SetLineInfo(reader as IJsonLineInfo);
+9 -9
View File
@@ -589,19 +589,19 @@ namespace Newtonsoft.Json.Linq
ClearItems(); ClearItems();
} }
internal void ReadTokenFrom(JsonReader r) internal void ReadTokenFrom(JsonReader reader)
{ {
int startDepth = r.Depth; int startDepth = reader.Depth;
if (!r.Read()) if (!reader.Read())
throw new Exception("Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
ReadContentFrom(r); ReadContentFrom(reader);
int endDepth = r.Depth; int endDepth = reader.Depth;
if (endDepth > startDepth) if (endDepth > startDepth)
throw new Exception("Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
} }
internal void ReadContentFrom(JsonReader r) internal void ReadContentFrom(JsonReader r)
@@ -908,10 +908,10 @@ namespace Newtonsoft.Json.Linq
OnAddingNew(args); OnAddingNew(args);
if (args.NewObject == null) if (args.NewObject == null)
throw new Exception("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType())); throw new JsonException("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType()));
if (!(args.NewObject is JToken)) if (!(args.NewObject is JToken))
throw new Exception("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof (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; JToken newItem = (JToken)args.NewObject;
Add(newItem); Add(newItem);
+6 -8
View File
@@ -289,14 +289,12 @@ namespace Newtonsoft.Json.Linq
if (reader.TokenType == JsonToken.None) if (reader.TokenType == JsonToken.None)
{ {
if (!reader.Read()) if (!reader.Read())
throw new Exception("Error reading JObject from JsonReader."); throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader.");
} }
if (reader.TokenType != JsonToken.StartObject) if (reader.TokenType != JsonToken.StartObject)
{ {
throw new Exception( throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
"Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(
CultureInfo.InvariantCulture, reader.TokenType));
} }
JObject o = new JObject(); JObject o = new JObject();
@@ -314,12 +312,12 @@ namespace Newtonsoft.Json.Linq
/// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns>
public static new JObject Parse(string json) public static new JObject Parse(string json)
{ {
JsonReader jsonReader = new JsonTextReader(new StringReader(json)); JsonReader reader = new JsonTextReader(new StringReader(json));
JObject o = Load(jsonReader); JObject o = Load(reader);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) if (reader.Read() && reader.TokenType != JsonToken.Comment)
throw new Exception("Additional text found in JSON string after parsing content."); throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
return o; return o;
} }
+8 -8
View File
@@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Linq
break; break;
case ']': case ']':
case ')': case ')':
throw new Exception("Unexpected character while parsing path: " + currentChar); throw new JsonException("Unexpected character while parsing path: " + currentChar);
case '.': case '.':
if (_currentIndex > currentPartStartIndex) if (_currentIndex > currentPartStartIndex)
{ {
@@ -58,7 +58,7 @@ namespace Newtonsoft.Json.Linq
break; break;
default: default:
if (followingIndexer) if (followingIndexer)
throw new Exception("Unexpected character following indexer: " + currentChar); throw new JsonException("Unexpected character following indexer: " + currentChar);
break; break;
} }
@@ -95,17 +95,17 @@ namespace Newtonsoft.Json.Linq
} }
else else
{ {
throw new Exception("Unexpected character while parsing path indexer: " + currentCharacter); throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
} }
_currentIndex++; _currentIndex++;
} }
if (!indexerClosed) if (!indexerClosed)
throw new Exception("Path ended with open indexer. Expected " + indexerCloseChar); throw new JsonException("Path ended with open indexer. Expected " + indexerCloseChar);
if (indexerLength == 0) if (indexerLength == 0)
throw new Exception("Empty path indexer."); throw new JsonException("Empty path indexer.");
string indexer = _expression.Substring(indexerStart, indexerLength); string indexer = _expression.Substring(indexerStart, indexerLength);
Parts.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); Parts.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture));
@@ -126,12 +126,12 @@ namespace Newtonsoft.Json.Linq
current = o[propertyName]; current = o[propertyName];
if (current == null && errorWhenNoMatch) if (current == null && errorWhenNoMatch)
throw new Exception("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName)); throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName));
} }
else else
{ {
if (errorWhenNoMatch) if (errorWhenNoMatch)
throw new Exception("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name)); throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name));
return null; return null;
} }
@@ -170,7 +170,7 @@ namespace Newtonsoft.Json.Linq
else else
{ {
if (errorWhenNoMatch) if (errorWhenNoMatch)
throw new Exception("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name)); throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name));
return null; return null;
} }
+6 -8
View File
@@ -120,18 +120,18 @@ namespace Newtonsoft.Json.Linq
internal override bool RemoveItem(JToken item) internal override bool RemoveItem(JToken item)
{ {
throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
} }
internal override void RemoveItemAt(int index) internal override void RemoveItemAt(int index)
{ {
throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
} }
internal override void InsertItem(int index, JToken item, bool skipParentCheck) internal override void InsertItem(int index, JToken item, bool skipParentCheck)
{ {
if (Value != null) if (Value != null)
throw new Exception("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
base.InsertItem(0, item, false); base.InsertItem(0, item, false);
} }
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Linq
internal override void ClearItems() internal override void ClearItems()
{ {
throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
} }
internal override bool DeepEquals(JToken node) internal override bool DeepEquals(JToken node)
@@ -227,12 +227,10 @@ namespace Newtonsoft.Json.Linq
if (reader.TokenType == JsonToken.None) if (reader.TokenType == JsonToken.None)
{ {
if (!reader.Read()) if (!reader.Read())
throw new Exception("Error reading JProperty from JsonReader."); throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader.");
} }
if (reader.TokenType != JsonToken.PropertyName) if (reader.TokenType != JsonToken.PropertyName)
throw new Exception( throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
"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); JProperty p = new JProperty((string)reader.Value);
p.SetLineInfo(reader as IJsonLineInfo); p.SetLineInfo(reader as IJsonLineInfo);
+6 -6
View File
@@ -1204,7 +1204,7 @@ namespace Newtonsoft.Json.Linq
if (reader.TokenType == JsonToken.None) if (reader.TokenType == JsonToken.None)
{ {
if (!reader.Read()) if (!reader.Read())
throw new Exception("Error reading JToken from JsonReader."); throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader.");
} }
if (reader.TokenType == JsonToken.StartObject) if (reader.TokenType == JsonToken.StartObject)
@@ -1223,7 +1223,7 @@ namespace Newtonsoft.Json.Linq
return new JValue(reader.Value); return new JValue(reader.Value);
// TODO: loading constructor and parameters? // TODO: loading constructor and parameters?
throw new Exception("Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
/// <summary> /// <summary>
@@ -1233,12 +1233,12 @@ namespace Newtonsoft.Json.Linq
/// <returns>A <see cref="JToken"/> populated from the string that contains JSON.</returns> /// <returns>A <see cref="JToken"/> populated from the string that contains JSON.</returns>
public static JToken Parse(string json) public static JToken Parse(string json)
{ {
JsonReader jsonReader = new JsonTextReader(new StringReader(json)); JsonReader reader = new JsonTextReader(new StringReader(json));
JToken t = Load(jsonReader); JToken t = Load(reader);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) if (reader.Read() && reader.TokenType != JsonToken.Comment)
throw new Exception("Additional text found in JSON string after parsing content."); throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content.");
return t; return t;
} }
@@ -98,6 +98,7 @@
<Compile Include="FormatterAssemblyStyle.cs" /> <Compile Include="FormatterAssemblyStyle.cs" />
<Compile Include="Formatting.cs" /> <Compile Include="Formatting.cs" />
<Compile Include="JsonConstructorAttribute.cs" /> <Compile Include="JsonConstructorAttribute.cs" />
<Compile Include="JsonException.cs" />
<Compile Include="JsonPosition.cs" /> <Compile Include="JsonPosition.cs" />
<Compile Include="Linq\JPropertyKeyedCollection.cs" /> <Compile Include="Linq\JPropertyKeyedCollection.cs" />
<Compile Include="SerializationBinder.cs" /> <Compile Include="SerializationBinder.cs" />
@@ -110,6 +110,7 @@
<Compile Include="FormatterAssemblyStyle.cs" /> <Compile Include="FormatterAssemblyStyle.cs" />
<Compile Include="Formatting.cs" /> <Compile Include="Formatting.cs" />
<Compile Include="JsonConstructorAttribute.cs" /> <Compile Include="JsonConstructorAttribute.cs" />
<Compile Include="JsonException.cs" />
<Compile Include="JsonPosition.cs" /> <Compile Include="JsonPosition.cs" />
<Compile Include="Linq\JPropertyDescriptor.cs" /> <Compile Include="Linq\JPropertyDescriptor.cs" />
<Compile Include="Linq\JPropertyKeyedCollection.cs" /> <Compile Include="Linq\JPropertyKeyedCollection.cs" />
@@ -117,6 +117,7 @@
<Compile Include="JsonConverter.cs" /> <Compile Include="JsonConverter.cs" />
<Compile Include="JsonConverterAttribute.cs" /> <Compile Include="JsonConverterAttribute.cs" />
<Compile Include="JsonConverterCollection.cs" /> <Compile Include="JsonConverterCollection.cs" />
<Compile Include="JsonException.cs" />
<Compile Include="JsonIgnoreAttribute.cs" /> <Compile Include="JsonIgnoreAttribute.cs" />
<Compile Include="JsonObjectAttribute.cs" /> <Compile Include="JsonObjectAttribute.cs" />
<Compile Include="JsonPosition.cs" /> <Compile Include="JsonPosition.cs" />
@@ -90,6 +90,7 @@
<Compile Include="JsonConverter.cs" /> <Compile Include="JsonConverter.cs" />
<Compile Include="JsonConverterAttribute.cs" /> <Compile Include="JsonConverterAttribute.cs" />
<Compile Include="JsonConverterCollection.cs" /> <Compile Include="JsonConverterCollection.cs" />
<Compile Include="JsonException.cs" />
<Compile Include="JsonIgnoreAttribute.cs" /> <Compile Include="JsonIgnoreAttribute.cs" />
<Compile Include="JsonObjectAttribute.cs" /> <Compile Include="JsonObjectAttribute.cs" />
<Compile Include="JsonPosition.cs" /> <Compile Include="JsonPosition.cs" />
@@ -103,6 +103,7 @@
<Compile Include="Converters\StringEnumConverter.cs" /> <Compile Include="Converters\StringEnumConverter.cs" />
<Compile Include="ConstructorHandling.cs" /> <Compile Include="ConstructorHandling.cs" />
<Compile Include="Converters\VersionConverter.cs" /> <Compile Include="Converters\VersionConverter.cs" />
<Compile Include="JsonException.cs" />
<Compile Include="DateFormatHandling.cs" /> <Compile Include="DateFormatHandling.cs" />
<Compile Include="DateParseHandling.cs" /> <Compile Include="DateParseHandling.cs" />
<Compile Include="DateTimeZoneHandling.cs" /> <Compile Include="DateTimeZoneHandling.cs" />
@@ -91,7 +91,7 @@ using System.Security;
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")] [assembly: AssemblyVersion("4.5.0.0")]
#if !PocketPC #if !PocketPC
[assembly: AssemblyFileVersion("4.5.3.14818")] [assembly: AssemblyFileVersion("4.5.3.14821")]
#endif #endif
[assembly: CLSCompliant(true)] [assembly: CLSCompliant(true)]
+19 -20
View File
@@ -83,7 +83,7 @@ namespace Newtonsoft.Json.Schema
private JsonSchema BuildSchema() private JsonSchema BuildSchema()
{ {
if (_reader.TokenType != JsonToken.StartObject) if (_reader.TokenType != JsonToken.StartObject)
throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
_reader.Read(); _reader.Read();
// empty schema object // empty schema object
@@ -105,13 +105,12 @@ namespace Newtonsoft.Json.Schema
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{ {
if (_reader.TokenType == JsonToken.StartObject) if (_reader.TokenType == JsonToken.StartObject)
throw new Exception("Found StartObject within the schema reference with the Id '{0}'" throw JsonReaderException.Create(_reader, "Found StartObject within the schema reference with the Id '{0}'".FormatWith(CultureInfo.InvariantCulture, id));
.FormatWith(CultureInfo.InvariantCulture, id));
} }
JsonSchema referencedSchema = _resolver.GetSchema(id); JsonSchema referencedSchema = _resolver.GetSchema(id);
if (referencedSchema == null) if (referencedSchema == null)
throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id)); throw new JsonException("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
return referencedSchema; return referencedSchema;
} }
@@ -237,7 +236,7 @@ namespace Newtonsoft.Json.Schema
private void ProcessEnum() private void ProcessEnum()
{ {
if (_reader.TokenType != JsonToken.StartArray) if (_reader.TokenType != JsonToken.StartArray)
throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
CurrentSchema.Enum = new List<JToken>(); CurrentSchema.Enum = new List<JToken>();
@@ -258,7 +257,7 @@ namespace Newtonsoft.Json.Schema
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{ {
if (_reader.TokenType != JsonToken.StartObject) if (_reader.TokenType != JsonToken.StartObject)
throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
string label = null; string label = null;
JToken value = null; JToken value = null;
@@ -277,21 +276,21 @@ namespace Newtonsoft.Json.Schema
label = (string) _reader.Value; label = (string) _reader.Value;
break; break;
default: default:
throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName)); throw JsonReaderException.Create(_reader, "Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
} }
} }
if (value == null) if (value == null)
throw new Exception("No value specified for JSON schema option."); throw new JsonException("No value specified for JSON schema option.");
if (CurrentSchema.Options.ContainsKey(value)) if (CurrentSchema.Options.ContainsKey(value))
throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value)); throw new JsonException("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
CurrentSchema.Options.Add(value, label); CurrentSchema.Options.Add(value, label);
} }
break; break;
default: default:
throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
} }
} }
@@ -313,13 +312,13 @@ namespace Newtonsoft.Json.Schema
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{ {
if (_reader.TokenType != JsonToken.String) if (_reader.TokenType != JsonToken.String)
throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
CurrentSchema.Identity.Add(_reader.Value.ToString()); CurrentSchema.Identity.Add(_reader.Value.ToString());
} }
break; break;
default: default:
throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
} }
} }
@@ -336,7 +335,7 @@ namespace Newtonsoft.Json.Schema
Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>(); Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>();
if (_reader.TokenType != JsonToken.StartObject) if (_reader.TokenType != JsonToken.StartObject)
throw new Exception("Expected start object token."); throw JsonReaderException.Create(_reader, "Expected StartObject token.");
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{ {
@@ -344,7 +343,7 @@ namespace Newtonsoft.Json.Schema
_reader.Read(); _reader.Read();
if (patternProperties.ContainsKey(propertyName)) if (patternProperties.ContainsKey(propertyName))
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
patternProperties.Add(propertyName, BuildSchema()); patternProperties.Add(propertyName, BuildSchema());
} }
@@ -368,7 +367,7 @@ namespace Newtonsoft.Json.Schema
} }
break; break;
default: default:
throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
} }
} }
@@ -377,7 +376,7 @@ namespace Newtonsoft.Json.Schema
IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>(); IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
if (_reader.TokenType != JsonToken.StartObject) if (_reader.TokenType != JsonToken.StartObject)
throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
{ {
@@ -385,7 +384,7 @@ namespace Newtonsoft.Json.Schema
_reader.Read(); _reader.Read();
if (properties.ContainsKey(propertyName)) if (properties.ContainsKey(propertyName))
throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
properties.Add(propertyName, BuildSchema()); properties.Add(propertyName, BuildSchema());
} }
@@ -406,14 +405,14 @@ namespace Newtonsoft.Json.Schema
while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
{ {
if (_reader.TokenType != JsonToken.String) if (_reader.TokenType != JsonToken.String)
throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
type = type | MapType(_reader.Value.ToString()); type = type | MapType(_reader.Value.ToString());
} }
return type; return type;
default: default:
throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); throw JsonReaderException.Create(_reader, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
} }
} }
@@ -421,7 +420,7 @@ namespace Newtonsoft.Json.Schema
{ {
JsonSchemaType mappedType; JsonSchemaType mappedType;
if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType)) if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); throw new JsonException("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
return mappedType; return mappedType;
} }
@@ -34,7 +34,7 @@ namespace Newtonsoft.Json.Schema
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable] [Serializable]
#endif #endif
public class JsonSchemaException : Exception public class JsonSchemaException : JsonException
{ {
/// <summary> /// <summary>
/// Gets the line number indicating where the error occurred. /// Gets the line number indicating where the error occurred.
@@ -238,7 +238,7 @@ namespace Newtonsoft.Json.Schema
// test for unresolved circular reference // test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type)) if (_stack.Any(tc => tc.Type == type))
{ {
throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
} }
JsonContract contract = ContractResolver.ResolveContract(type); JsonContract contract = ContractResolver.ResolveContract(type);
@@ -344,7 +344,7 @@ namespace Newtonsoft.Json.Schema
CurrentSchema.Type = JsonSchemaType.Any; CurrentSchema.Type = JsonSchemaType.Any;
break; break;
default: default:
throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
} }
} }
@@ -457,7 +457,7 @@ namespace Newtonsoft.Json.Schema
case TypeCode.String: case TypeCode.String:
return schemaType | JsonSchemaType.String; return schemaType | JsonSchemaType.String;
default: default:
throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
} }
} }
} }
@@ -385,7 +385,7 @@ namespace Newtonsoft.Json.Serialization
IList<ConstructorInfo> markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList(); IList<ConstructorInfo> markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList();
if (markedConstructors.Count > 1) if (markedConstructors.Count > 1)
throw new Exception("Multiple constructors with the JsonConstructorAttribute."); throw new JsonException("Multiple constructors with the JsonConstructorAttribute.");
else if (markedConstructors.Count == 1) else if (markedConstructors.Count == 1)
return markedConstructors[0]; return markedConstructors[0];
@@ -792,26 +792,26 @@ namespace Newtonsoft.Json.Serialization
return false; return false;
if (currentCallback != null) if (currentCallback != null)
throw new Exception("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); 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) if (prevAttributeType != null)
throw new Exception("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); 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) if (method.IsVirtual)
throw new Exception("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); 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)) if (method.ReturnType != typeof(void))
throw new Exception("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method));
if (attributeType == typeof(OnErrorAttribute)) if (attributeType == typeof(OnErrorAttribute))
{ {
if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext)) if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
throw new Exception("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))); 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 else
{ {
if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext)) if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
throw new Exception("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, 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; prevAttributeType = attributeType;
@@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Serialization
else if (context is JsonSerializerProxy) else if (context is JsonSerializerProxy)
internalSerializer = ((JsonSerializerProxy) context).GetInternalSerializer(); internalSerializer = ((JsonSerializerProxy) context).GetInternalSerializer();
else else
throw new Exception("The DefaultReferenceResolver can only be used internally."); throw new JsonException("The DefaultReferenceResolver can only be used internally.");
return internalSerializer.DefaultReferenceMappings; return internalSerializer.DefaultReferenceMappings;
} }
@@ -73,11 +73,11 @@ namespace Newtonsoft.Json.Serialization
if (value == null) if (value == null)
{ {
if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo))) if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
throw new Exception("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
} }
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType())) else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
{ {
throw new Exception("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType())); throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
} }
#endif #endif
@@ -71,7 +71,7 @@ namespace Newtonsoft.Json.Serialization
if (contract.ContractType == JsonContractType.Array) if (contract.ContractType == JsonContractType.Array)
PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, (JsonArrayContract) contract); PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, (JsonArrayContract) contract);
else else
throw CreateSerializationException(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
else if (reader.TokenType == JsonToken.StartObject) else if (reader.TokenType == JsonToken.StartObject)
{ {
@@ -90,11 +90,11 @@ namespace Newtonsoft.Json.Serialization
else if (contract.ContractType == JsonContractType.Object) else if (contract.ContractType == JsonContractType.Object)
PopulateObject(target, reader, (JsonObjectContract) contract, id); PopulateObject(target, reader, (JsonObjectContract) contract, id);
else else
throw CreateSerializationException(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
else else
{ {
throw CreateSerializationException(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); throw JsonSerializationException.Create(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
} }
} }
@@ -118,7 +118,7 @@ namespace Newtonsoft.Json.Serialization
if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null, false)) if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null, false))
{ {
if (contract != null && !contract.IsNullable) if (contract != null && !contract.IsNullable)
throw CreateSerializationException(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw JsonSerializationException.Create(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
return null; return null;
} }
@@ -280,28 +280,11 @@ namespace Newtonsoft.Json.Serialization
// ignore // ignore
break; break;
default: default:
throw CreateSerializationException(reader, "Unexpected token while deserializing object: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType);
} }
} while (reader.Read()); } while (reader.Read());
throw CreateSerializationException(reader, "Unexpected end when deserializing object."); throw JsonSerializationException.Create(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) private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter)
@@ -352,7 +335,7 @@ namespace Newtonsoft.Json.Serialization
{ {
CheckedRead(reader); CheckedRead(reader);
if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null) if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null)
throw CreateSerializationException(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); throw JsonSerializationException.Create(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; string reference = (reader.Value != null) ? reader.Value.ToString() : null;
@@ -361,7 +344,7 @@ namespace Newtonsoft.Json.Serialization
if (reference != null) if (reference != null)
{ {
if (reader.TokenType == JsonToken.PropertyName) if (reader.TokenType == JsonToken.PropertyName)
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)); throw JsonSerializationException.Create(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); return Serializer.ReferenceResolver.ResolveReference(this, reference);
} }
@@ -388,14 +371,14 @@ namespace Newtonsoft.Json.Serialization
} }
catch (Exception ex) catch (Exception ex)
{ {
throw CreateSerializationException(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex);
} }
if (specifiedType == null) if (specifiedType == null)
throw CreateSerializationException(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName));
if (objectType != null && !objectType.IsAssignableFrom(specifiedType)) if (objectType != null && !objectType.IsAssignableFrom(specifiedType))
throw CreateSerializationException(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName));
objectType = specifiedType; objectType = specifiedType;
contract = GetContractSafe(specifiedType); contract = GetContractSafe(specifiedType);
@@ -434,7 +417,7 @@ namespace Newtonsoft.Json.Serialization
return CreateJObject(reader); return CreateJObject(reader);
if (contract == null) if (contract == null)
throw CreateSerializationException(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType));
switch (contract.ContractType) switch (contract.ContractType)
{ {
@@ -474,7 +457,7 @@ namespace Newtonsoft.Json.Serialization
#endif #endif
} }
throw CreateSerializationException(reader, @"Cannot deserialize JSON object (i.e. {{""name"":""value""}}) into type '{0}'. throw JsonSerializationException.Create(reader, @"Cannot deserialize JSON object (i.e. {{""name"":""value""}}) into type '{0}'.
The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List<T>) or a dictionary type (i.e. Dictionary<TKey, TValue>). The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List<T>) or a dictionary type (i.e. Dictionary<TKey, TValue>).
To force JSON objects to deserialize add the JsonObjectAttribute to the type.".FormatWith(CultureInfo.InvariantCulture, objectType)); To force JSON objects to deserialize add the JsonObjectAttribute to the type.".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
@@ -482,11 +465,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type.".F
private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract)
{ {
if (contract == null) if (contract == null)
throw CreateSerializationException(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType));
JsonArrayContract arrayContract = contract as JsonArrayContract; JsonArrayContract arrayContract = contract as JsonArrayContract;
if (arrayContract == null) if (arrayContract == null)
throw CreateSerializationException(reader, @"Cannot deserialize JSON array (i.e. [1,2,3]) into type '{0}'. throw JsonSerializationException.Create(reader, @"Cannot deserialize JSON array (i.e. [1,2,3]) into type '{0}'.
The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList.
To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".FormatWith(CultureInfo.InvariantCulture, objectType)); To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".FormatWith(CultureInfo.InvariantCulture, objectType));
@@ -496,7 +479,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
private void CheckedRead(JsonReader reader) private void CheckedRead(JsonReader reader)
{ {
if (!reader.Read()) if (!reader.Read())
throw CreateSerializationException(reader, "Unexpected end when deserializing object."); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
} }
private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string reference) private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string reference)
@@ -560,7 +543,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
} }
catch (Exception ex) catch (Exception ex)
{ {
throw CreateSerializationException(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex); throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex);
} }
} }
@@ -672,7 +655,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
(!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
dictionary = contract.DefaultCreator(); dictionary = contract.DefaultCreator();
else else
throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
IWrappedDictionary dictionaryWrapper = contract.CreateWrapper(dictionary); IWrappedDictionary dictionaryWrapper = contract.CreateWrapper(dictionary);
@@ -707,7 +690,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
} }
catch (Exception ex) catch (Exception 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); throw JsonSerializationException.Create(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) if (contract.DictionaryValueContract == null)
@@ -716,7 +699,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
JsonConverter dictionaryValueConverter = GetConverter(contract.DictionaryValueContract, null); JsonConverter dictionaryValueConverter = GetConverter(contract.DictionaryValueContract, null);
if (!ReadForType(reader, contract.DictionaryValueContract, dictionaryValueConverter != null, false)) if (!ReadForType(reader, contract.DictionaryValueContract, dictionaryValueConverter != null, false))
throw CreateSerializationException(reader, "Unexpected end when deserializing object."); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, contract.DictionaryValueContract, dictionaryValueConverter); dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, contract.DictionaryValueContract, dictionaryValueConverter);
} }
@@ -735,11 +718,11 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
return dictionary.UnderlyingDictionary; return dictionary.UnderlyingDictionary;
default: default:
throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
} }
} while (reader.Read()); } while (reader.Read());
throw CreateSerializationException(reader, "Unexpected end when deserializing object."); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
} }
private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract) private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract)
@@ -747,14 +730,14 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
return CollectionUtils.CreateAndPopulateList(contract.CreatedType, (l, isTemporaryListReference) => return CollectionUtils.CreateAndPopulateList(contract.CreatedType, (l, isTemporaryListReference) =>
{ {
if (reference != null && isTemporaryListReference) if (reference != null && isTemporaryListReference)
throw CreateSerializationException(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw JsonSerializationException.Create(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
#if !PocketPC #if !PocketPC
if (contract.OnSerializing != null && isTemporaryListReference) if (contract.OnSerializing != null && isTemporaryListReference)
throw CreateSerializationException(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
#endif #endif
if (contract.OnError != null && isTemporaryListReference) if (contract.OnError != null && isTemporaryListReference)
throw CreateSerializationException(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw JsonSerializationException.Create(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
PopulateList(contract.CreateWrapper(l), reader, reference, contract); PopulateList(contract.CreateWrapper(l), reader, reference, contract);
}); });
@@ -821,7 +804,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
} }
} }
throw CreateSerializationException(reader, "Unexpected end when deserializing array."); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing array.");
} }
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE) #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
@@ -831,7 +814,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For
if (!JsonTypeReflector.FullyTrusted) if (!JsonTypeReflector.FullyTrusted)
{ {
throw CreateSerializationException(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data. throw JsonSerializationException.Create(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data.
To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, objectType)); To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
@@ -845,7 +828,7 @@ To fix this error either change the environment to be fully trusted, change the
case JsonToken.PropertyName: case JsonToken.PropertyName:
string memberName = reader.Value.ToString(); string memberName = reader.Value.ToString();
if (!reader.Read()) if (!reader.Read())
throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
serializationInfo.AddValue(memberName, JToken.ReadFrom(reader)); serializationInfo.AddValue(memberName, JToken.ReadFrom(reader));
break; break;
@@ -855,12 +838,12 @@ To fix this error either change the environment to be fully trusted, change the
exit = true; exit = true;
break; break;
default: default:
throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
} }
} while (!exit && reader.Read()); } while (!exit && reader.Read());
if (contract.ISerializableCreator == null) if (contract.ISerializableCreator == null)
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)); throw JsonSerializationException.Create(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); object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context);
@@ -881,13 +864,13 @@ To fix this error either change the environment to be fully trusted, change the
IDynamicMetaObjectProvider newObject = null; IDynamicMetaObjectProvider newObject = null;
if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract()) if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract())
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)); throw JsonSerializationException.Create(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 && if (contract.DefaultCreator != null &&
(!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator(); newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator();
else else
throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
if (id != null) if (id != null)
Serializer.ReferenceResolver.AddReference(this, id, newObject); Serializer.ReferenceResolver.AddReference(this, id, newObject);
@@ -907,7 +890,7 @@ To fix this error either change the environment to be fully trusted, change the
try try
{ {
if (!reader.Read()) if (!reader.Read())
throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); 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 // first attempt to find a settable property, otherwise fall back to a dynamic set without type
JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);
@@ -945,7 +928,7 @@ To fix this error either change the environment to be fully trusted, change the
exit = true; exit = true;
break; break;
default: default:
throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
} }
} while (!exit && reader.Read()); } while (!exit && reader.Read());
@@ -960,7 +943,7 @@ To fix this error either change the environment to be fully trusted, change the
object newObject = null; object newObject = null;
if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract()) if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract())
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)); throw JsonSerializationException.Create(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) if (contract.OverrideConstructor != null)
{ {
@@ -984,7 +967,7 @@ To fix this error either change the environment to be fully trusted, change the
} }
if (newObject == null) if (newObject == null)
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)); 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, contract.UnderlyingType));
PopulateObject(newObject, reader, contract, id); PopulateObject(newObject, reader, contract, id);
return newObject; return newObject;
@@ -1095,7 +1078,7 @@ To fix this error either change the environment to be fully trusted, change the
JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter); JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter);
if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false)) if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false))
throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
if (!property.Ignored) if (!property.Ignored)
propertyValues[property] = CreateValueProperty(reader, property, propertyConverter, null, true, null); propertyValues[property] = CreateValueProperty(reader, property, propertyConverter, null, true, null);
@@ -1105,10 +1088,10 @@ To fix this error either change the environment to be fully trusted, change the
else else
{ {
if (!reader.Read()) if (!reader.Read())
throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name));
reader.Skip(); reader.Skip();
} }
@@ -1119,7 +1102,7 @@ To fix this error either change the environment to be fully trusted, change the
exit = true; exit = true;
break; break;
default: default:
throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
} }
} while (!exit && reader.Read()); } while (!exit && reader.Read());
@@ -1201,7 +1184,7 @@ To fix this error either change the environment to be fully trusted, change the
if (property == null) if (property == null)
{ {
if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) if (Serializer.MissingMemberHandling == MissingMemberHandling.Error)
throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name));
reader.Skip(); reader.Skip();
continue; continue;
@@ -1213,7 +1196,7 @@ To fix this error either change the environment to be fully trusted, change the
JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter); JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter);
if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false)) if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false))
throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
SetPropertyPresence(reader, property, propertiesPresence); SetPropertyPresence(reader, property, propertiesPresence);
@@ -1243,7 +1226,7 @@ To fix this error either change the environment to be fully trusted, change the
{ {
case PropertyPresence.None: case PropertyPresence.None:
if (property.Required == Required.AllowNull || property.Required == Required.Always) if (property.Required == Required.AllowNull || property.Required == Required.Always)
throw CreateSerializationException(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); throw JsonSerializationException.Create(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));
if (property.PropertyContract == null) if (property.PropertyContract == null)
property.PropertyContract = GetContractSafe(property.PropertyType); property.PropertyContract = GetContractSafe(property.PropertyType);
@@ -1254,7 +1237,7 @@ To fix this error either change the environment to be fully trusted, change the
break; break;
case PropertyPresence.Null: case PropertyPresence.Null:
if (property.Required == Required.Always) if (property.Required == Required.Always)
throw CreateSerializationException(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); throw JsonSerializationException.Create(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName));
break; break;
} }
} }
@@ -1275,11 +1258,11 @@ To fix this error either change the environment to be fully trusted, change the
// ignore // ignore
break; break;
default: default:
throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType);
} }
} while (reader.Read()); } while (reader.Read());
throw CreateSerializationException(reader, "Unexpected end when deserializing object."); throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object.");
} }
private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary<JsonProperty, PropertyPresence> requiredProperties) private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary<JsonProperty, PropertyPresence> requiredProperties)
@@ -136,7 +136,7 @@ namespace Newtonsoft.Json.Utilities
} }
else else
{ {
throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType())); throw new ArgumentException("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()), "list");
} }
} }
@@ -167,7 +167,7 @@ namespace Newtonsoft.Json.Utilities
#endif #endif
else else
{ {
throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType())); throw new ArgumentException("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType()), "dictionary");
} }
} }
@@ -237,7 +237,7 @@ namespace Newtonsoft.Json.Utilities
} }
if (list == null) if (list == null)
throw new Exception("Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, listType)); throw new InvalidOperationException("Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, listType));
populateList(list, isReadOnlyOrFixedSize); populateList(list, isReadOnlyOrFixedSize);
@@ -170,7 +170,7 @@ namespace Newtonsoft.Json.Utilities
int IList.IndexOf(object value) int IList.IndexOf(object value)
{ {
if (_genericCollection != null) if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support IndexOf."); throw new InvalidOperationException("Wrapped ICollection<T> does not support IndexOf.");
if (IsCompatibleObject(value)) if (IsCompatibleObject(value))
return _list.IndexOf((T)value); return _list.IndexOf((T)value);
@@ -181,7 +181,7 @@ namespace Newtonsoft.Json.Utilities
void IList.RemoveAt(int index) void IList.RemoveAt(int index)
{ {
if (_genericCollection != null) if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support RemoveAt."); throw new InvalidOperationException("Wrapped ICollection<T> does not support RemoveAt.");
_list.RemoveAt(index); _list.RemoveAt(index);
} }
@@ -189,7 +189,7 @@ namespace Newtonsoft.Json.Utilities
void IList.Insert(int index, object value) void IList.Insert(int index, object value)
{ {
if (_genericCollection != null) if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support Insert."); throw new InvalidOperationException("Wrapped ICollection<T> does not support Insert.");
VerifyValueType(value); VerifyValueType(value);
_list.Insert(index, (T)value); _list.Insert(index, (T)value);
@@ -218,14 +218,14 @@ namespace Newtonsoft.Json.Utilities
get get
{ {
if (_genericCollection != null) if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support indexer."); throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer.");
return _list[index]; return _list[index];
} }
set set
{ {
if (_genericCollection != null) if (_genericCollection != null)
throw new Exception("Wrapped ICollection<T> does not support indexer."); throw new InvalidOperationException("Wrapped ICollection<T> does not support indexer.");
VerifyValueType(value); VerifyValueType(value);
_list[index] = (T)value; _list[index] = (T)value;
@@ -376,7 +376,7 @@ namespace Newtonsoft.Json.Utilities
return EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType); return EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType);
#endif #endif
throw new Exception("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType)); throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
} }
#endregion #endregion
@@ -445,7 +445,7 @@ namespace Newtonsoft.Json.Utilities
return null; return null;
} }
throw new Exception("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType));
} }
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE) #if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
@@ -464,7 +464,7 @@ namespace Newtonsoft.Json.Utilities
else if (nullableValue is SqlDateTime) else if (nullableValue is SqlDateTime)
return ToValue((SqlDateTime)nullableValue); return ToValue((SqlDateTime)nullableValue);
throw new Exception("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType())); throw new ArgumentException("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType()));
} }
#endif #endif
@@ -130,7 +130,7 @@ namespace Newtonsoft.Json.Utilities
ReflectionUtils.EmptyTypes, null); ReflectionUtils.EmptyTypes, null);
if (constructorInfo == null) if (constructorInfo == null)
throw new Exception("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); throw new ArgumentException("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type));
generator.Emit(OpCodes.Newobj, constructorInfo); generator.Emit(OpCodes.Newobj, constructorInfo);
} }
@@ -152,7 +152,7 @@ namespace Newtonsoft.Json.Utilities
{ {
MethodInfo getMethod = propertyInfo.GetGetMethod(true); MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod == null) if (getMethod == null)
throw new Exception("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); throw new ArgumentException("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name));
if (!getMethod.IsStatic) if (!getMethod.IsStatic)
generator.PushInstance(propertyInfo.DeclaringType); generator.PushInstance(propertyInfo.DeclaringType);
@@ -39,7 +39,7 @@ namespace Newtonsoft.Json.Utilities
{ {
Type binderType = Type.GetType(BinderTypeName, false); Type binderType = Type.GetType(BinderTypeName, false);
if (binderType == null) if (binderType == null)
throw new Exception("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)); 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 // None
_getCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0); _getCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0);
+2 -2
View File
@@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Utilities
Type enumType = typeof(T); Type enumType = typeof(T);
if (!enumType.IsDefined(typeof(FlagsAttribute), false)) if (!enumType.IsDefined(typeof(FlagsAttribute), false))
throw new Exception("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType)); throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType));
Type underlyingType = Enum.GetUnderlyingType(value.GetType()); Type underlyingType = Enum.GetUnderlyingType(value.GetType());
@@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Utilities
} }
catch (OverflowException e) catch (OverflowException e)
{ {
throw new Exception( throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}", string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}",
Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e); Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e);
} }