-Increment version to 4.0.7

-Fixed circular reference error when serializing nullable structs
-Fixed JsonReader.ReadAsXXX methods not converting string values
This commit is contained in:
JamesNK
2012-01-24 09:12:32 +00:00
parent b82d26028d
commit 3d43fc9c4f
13 changed files with 590 additions and 128 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
<metadata> <metadata>
<id>Newtonsoft.Json</id> <id>Newtonsoft.Json</id>
<title>Json.NET</title> <title>Json.NET</title>
<version>4.0.6</version> <version>4.0.7</version>
<authors>James Newton-King</authors> <authors>James Newton-King</authors>
<description>Json.NET is a popular high-performance JSON framework for .NET</description> <description>Json.NET is a popular high-performance JSON framework for .NET</description>
<language>en-US</language> <language>en-US</language>
+2 -2
View File
@@ -1,6 +1,6 @@
properties { properties {
$zipFileName = "Json40r6.zip" $zipFileName = "Json40r7.zip"
$majorVersion = "4.0.6" $majorVersion = "4.0.7"
$version = GetVersion $majorVersion $version = GetVersion $majorVersion
$signAssemblies = $false $signAssemblies = $false
$signKeyPath = "D:\Development\Releases\newtonsoft.snk" $signKeyPath = "D:\Development\Releases\newtonsoft.snk"
+96 -40
View File
@@ -1302,6 +1302,23 @@ bye", reader.Value);
Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
} }
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22.")]
public void ReadAsDateTimeOffsetBadString()
{
string json = @"{""Offset"":""blablahbla""}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDateTimeOffset();
}
[Test] [Test]
public void ReadAsDateTimeOffsetHoursOnly() public void ReadAsDateTimeOffsetHoursOnly()
{ {
@@ -1346,46 +1363,6 @@ bye", reader.Value);
Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
} }
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 0, position 0.")]
public void MatchWithInsufficentCharacters()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nul"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 0, position 0.")]
public void MatchWithWrongCharacters()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 1, position 4.")]
public void MatchWithNoTrailingSeperator()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6.")]
public void UnclosedComment()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing comment. Expected: *, got s. Line 1, position 1.")]
public void BadCommentStart()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf"));
reader.Read();
}
[Test] [Test]
public void ReadAsDateTimeOffsetIsoDate() public void ReadAsDateTimeOffsetIsoDate()
{ {
@@ -1459,6 +1436,85 @@ bye", reader.Value);
} }
#endif #endif
[Test]
public void ReadAsDecimalInt()
{
string json = @"{""Name"":1}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(1, reader.Value);
}
[Test]
[ExpectedException(typeof(FormatException), ExpectedMessage = "Input string was not in a correct format.")]
public void ReadAsIntDecimal()
{
string json = @"{""Name"": 1.1}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsInt32();
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 0, position 0.")]
public void MatchWithInsufficentCharacters()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nul"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 0, position 0.")]
public void MatchWithWrongCharacters()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing null value. Line 1, position 4.")]
public void MatchWithNoTrailingSeperator()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6.")]
public void UnclosedComment()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf"));
reader.Read();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error parsing comment. Expected: *, got s. Line 1, position 1.")]
public void BadCommentStart()
{
JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf"));
reader.Read();
}
[Test] [Test]
public void ReadAsDecimal() public void ReadAsDecimal()
{ {
@@ -31,6 +31,7 @@ using Newtonsoft.Json;
using System.IO; using System.IO;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
namespace Newtonsoft.Json.Tests.Linq namespace Newtonsoft.Json.Tests.Linq
{ {
@@ -111,6 +112,65 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsFalse(jsonReader.Read()); Assert.IsFalse(jsonReader.Read());
} }
} }
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22.")]
public void ReadAsDateTimeOffsetBadString()
{
string json = @"{""Offset"":""blablahbla""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDateTimeOffset();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading date. Expected bytes but got Boolean. Line 1, position 14.")]
public void ReadAsDateTimeOffsetBoolean()
{
string json = @"{""Offset"":true}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDateTimeOffset();
}
[Test]
public void ReadAsDateTimeOffsetString()
{
string json = @"{""Offset"":""2012-01-24T03:50Z""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDateTimeOffset();
Assert.AreEqual(JsonToken.Date, reader.TokenType);
Assert.AreEqual(typeof (DateTimeOffset), reader.ValueType);
Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), reader.Value);
}
#endif #endif
[Test] [Test]
@@ -331,5 +391,189 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); Assert.AreEqual(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data);
} }
} }
[Test]
public void DeserializeStringInt()
{
string json = @"{
""PreProperty"": ""99"",
""PostProperty"": ""-1""
}";
JObject o = JObject.Parse(json);
JsonSerializer serializer = new JsonSerializer();
using (JsonReader nodeReader = o.CreateReader())
{
MyClass c = serializer.Deserialize<MyClass>(nodeReader);
Assert.AreEqual(99, c.PreProperty);
Assert.AreEqual(-1, c.PostProperty);
}
}
[Test]
public void ReadAsDecimalInt()
{
string json = @"{""Name"":1}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(1, reader.Value);
}
[Test]
public void ReadAsInt32Int()
{
string json = @"{""Name"":1}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsInt32();
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to integer: hi. Line 1, position 12.")]
public void ReadAsInt32BadString()
{
string json = @"{""Name"":""hi""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsInt32();
Assert.AreEqual(JsonToken.Integer, reader.TokenType);
Assert.AreEqual(typeof(int), reader.ValueType);
Assert.AreEqual(1, reader.Value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading integer. Expected a number but got Boolean. Line 1, position 12.")]
public void ReadAsInt32Boolean()
{
string json = @"{""Name"":true}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsInt32();
}
[Test]
public void ReadAsDecimalString()
{
string json = @"{""Name"":""1.1""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Float, reader.TokenType);
Assert.AreEqual(typeof(decimal), reader.ValueType);
Assert.AreEqual(1.1m, reader.Value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Could not convert string to decimal: blah. Line 1, position 14.")]
public void ReadAsDecimalBadString()
{
string json = @"{""Name"":""blah""}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Error reading decimal. Expected a number but got Boolean. Line 1, position 12.")]
public void ReadAsDecimalBoolean()
{
string json = @"{""Name"":true}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
}
[Test]
public void ReadAsDecimalNull()
{
string json = @"{""Name"":null}";
JObject o = JObject.Parse(json);
JsonReader reader = o.CreateReader();
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
reader.ReadAsDecimal();
Assert.AreEqual(JsonToken.Null, reader.TokenType);
Assert.AreEqual(null, reader.ValueType);
Assert.AreEqual(null, reader.Value);
}
} }
} }
@@ -64,7 +64,7 @@ using System.Runtime.InteropServices;
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.0.5.0")] [assembly: AssemblyVersion("4.0.7.0")]
#if !PocketPC #if !PocketPC
[assembly: AssemblyFileVersion("4.0.5.14519")] [assembly: AssemblyFileVersion("4.0.7.14524")]
#endif #endif
@@ -1044,7 +1044,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null. Line 6, position 2.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Required property 'FirstName' expects a value but got null. Line 6, position 2.")]
public void DeserializeRequiredMembersClassNullRequiredValueProperty() public void DeserializeRequiredMembersClassNullRequiredValueProperty()
{ {
string json = @"{ string json = @"{
@@ -1074,7 +1074,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON. Line 3, position 2.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Required property 'LastName' not found in JSON. Line 3, position 2.")]
public void RequiredMembersClassMissingRequiredProperty() public void RequiredMembersClassMissingRequiredProperty()
{ {
string json = @"{ string json = @"{
@@ -1160,7 +1160,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14.")]
public void DeserializeInterfaceProperty() public void DeserializeInterfaceProperty()
{ {
InterfacePropertyTestClass testClass = new InterfacePropertyTestClass(); InterfacePropertyTestClass testClass = new InterfacePropertyTestClass();
@@ -1832,7 +1832,7 @@ keyword such as type of business.""
#endif #endif
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 15.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 15.")]
public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments() 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)\/""}";
@@ -1872,7 +1872,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array into type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON array into type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")]
public void CannotDeserializeArrayIntoObject() public void CannotDeserializeArrayIntoObject()
{ {
string json = @"[]"; string json = @"[]";
@@ -1881,7 +1881,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")]
public void CannotDeserializeObjectIntoArray() public void CannotDeserializeObjectIntoArray()
{ {
string json = @"{}"; string json = @"{}";
@@ -1890,7 +1890,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1.")]
public void CannotPopulateArrayIntoObject() public void CannotPopulateArrayIntoObject()
{ {
string json = @"[]"; string json = @"[]";
@@ -1899,7 +1899,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2.")]
public void CannotPopulateObjectIntoArray() public void CannotPopulateObjectIntoArray()
{ {
string json = @"{}"; string json = @"{}";
@@ -1931,14 +1931,14 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15.")] [ExpectedException(typeof (JsonReaderException), ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15.")]
public void DeserializeEnsureTypeEmptyStringToIntError() public void DeserializeEnsureTypeEmptyStringToIntError()
{ {
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}"); JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}");
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17.")]
public void DeserializeEnsureTypeNullToIntError() public void DeserializeEnsureTypeNullToIntError()
{ {
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}"); JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:null}");
@@ -2053,7 +2053,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Line 2, position 46.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Line 2, position 46.")]
public void DeserializePersonKeyedDictionary() public void DeserializePersonKeyedDictionary()
{ {
string json = string json =
@@ -2318,7 +2318,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6.")]
public void DeserializeDictionaryWithNoDefaultConstructor() public void DeserializeDictionaryWithNoDefaultConstructor()
{ {
string json = "{key1:'value',key2:'value',key3:'value'}"; string json = "{key1:'value',key2:'value',key3:'value'}";
@@ -3267,7 +3267,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11.")]
public void SerializeRefAdditionalContent() public void SerializeRefAdditionalContent()
{ {
//Additional text found in JSON string after finishing deserializing object. //Additional text found in JSON string after finishing deserializing object.
@@ -3286,7 +3286,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string or null value. Line 5, position 14.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string or null value. Line 5, position 14.")]
public void SerializeRefBadType() public void SerializeRefBadType()
{ {
//Additional text found in JSON string after finishing deserializing object. //Additional text found in JSON string after finishing deserializing object.
@@ -4280,7 +4280,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4.")]
public void DeserializeNullDateTimeValueTest() public void DeserializeNullDateTimeValueTest()
{ {
JsonConvert.DeserializeObject("null", typeof (DateTime)); JsonConvert.DeserializeObject("null", typeof (DateTime));
@@ -5020,7 +5020,7 @@ keyword such as type of business.""
[Test] [Test]
public void DeserializeByteArrayWithTypeNameHandling() public void DeserializeByteArrayWithTypeNameHandling()
{ {
TestObject test = new TestObject("Test", new byte[] { 72, 63, 62, 71, 92, 55 }); TestObject test = new TestObject("Test", new byte[] {72, 63, 62, 71, 92, 55});
JsonSerializer serializer = new JsonSerializer(); JsonSerializer serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All; serializer.TypeNameHandling = TypeNameHandling.All;
@@ -5042,7 +5042,7 @@ keyword such as type of business.""
TestObject newObject = (TestObject) serializer.Deserialize(bsonReader); TestObject newObject = (TestObject) serializer.Deserialize(bsonReader);
Assert.AreEqual("Test", newObject.Name); Assert.AreEqual("Test", newObject.Name);
Assert.AreEqual(new byte[] { 72, 63, 62, 71, 92, 55 }, newObject.Data); Assert.AreEqual(new byte[] {72, 63, 62, 71, 92, 55}, newObject.Data);
} }
} }
@@ -5077,7 +5077,7 @@ keyword such as type of business.""
[Test] [Test]
public void ReadForTypeHackFixDecimal() public void ReadForTypeHackFixDecimal()
{ {
IList<decimal> d1 = new List<decimal> { 1.1m}; IList<decimal> d1 = new List<decimal> {1.1m};
string json = JsonConvert.SerializeObject(d1); string json = JsonConvert.SerializeObject(d1);
@@ -5090,7 +5090,7 @@ keyword such as type of business.""
[Test] [Test]
public void ReadForTypeHackFixDateTimeOffset() public void ReadForTypeHackFixDateTimeOffset()
{ {
IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> { null }; IList<DateTimeOffset?> d1 = new List<DateTimeOffset?> {null};
string json = JsonConvert.SerializeObject(d1); string json = JsonConvert.SerializeObject(d1);
@@ -5103,7 +5103,7 @@ keyword such as type of business.""
[Test] [Test]
public void ReadForTypeHackFixByteArray() public void ReadForTypeHackFixByteArray()
{ {
IList<byte[]> d1 = new List<byte[]> { null }; IList<byte[]> d1 = new List<byte[]> {null};
string json = JsonConvert.SerializeObject(d1); string json = JsonConvert.SerializeObject(d1);
@@ -5131,7 +5131,7 @@ keyword such as type of business.""
} }
[Test] [Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7.")] [ExpectedException(typeof (JsonSerializationException), ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7.")]
public void DeserializeNullInt() public void DeserializeNullInt()
{ {
string json = @"[ string json = @"[
@@ -5144,6 +5144,60 @@ keyword such as type of business.""
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. // JsonSerializationException : Error converting value {null} to type 'System.Int32'. Line 5, position 7.
} }
[Test]
public void SerializeNullableWidgetStruct()
{
Widget widget = new Widget {Id = new WidgetId {Value = "id"}};
string json = JsonConvert.SerializeObject(widget);
Assert.AreEqual(@"{""Id"":{""Value"":""id""}}", json);
}
[Test]
public void DeserializeNullableWidgetStruct()
{
string json = @"{""Id"":{""Value"":""id""}}";
Widget w = JsonConvert.DeserializeObject<Widget>(json);
Assert.AreEqual(new WidgetId { Value = "id" }, w.Id);
Assert.AreEqual(new WidgetId { Value = "id" }, w.Id.Value);
Assert.AreEqual("id", w.Id.Value.Value);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected token when reading integer: Boolean. Line 2, position 22.")]
public void DeserializeBoolInt()
{
string json = @"{
""PreProperty"": true,
""PostProperty"": ""-1""
}";
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
}
[Test]
[ExpectedException(typeof(JsonReaderException), ExpectedMessage = "Unexpected end when reading integer. Line 2, position 18.")]
public void DeserializeUnexpectedEndInt()
{
string json = @"{
""PreProperty"": ";
JsonConvert.DeserializeObject<TestObjects.MyClass>(json);
}
}
public class Widget
{
public WidgetId? Id { get; set; }
}
public struct WidgetId
{
public string Value { get; set; }
} }
public class DecimalTestClass public class DecimalTestClass
@@ -5178,12 +5232,12 @@ keyword such as type of business.""
public Uri Uri { get; set; } public Uri Uri { get; set; }
} }
class Aa internal class Aa
{ {
public int no; public int no;
} }
class Bb : Aa internal class Bb : Aa
{ {
public bool no; public bool no;
} }
@@ -5198,8 +5252,7 @@ keyword such as type of business.""
[JsonProperty] [JsonProperty]
public string Name { get; set; } public string Name { get; set; }
[JsonProperty] [JsonProperty] public ConcurrentDictionary<string, Component> Components;
public ConcurrentDictionary<string, Component> Components;
public GameObject() public GameObject()
{ {
@@ -5212,7 +5265,7 @@ keyword such as type of business.""
public class Component public class Component
{ {
[JsonIgnore] // Ignore circular reference [JsonIgnore] // Ignore circular reference
public GameObject GameObject { get; set; } public GameObject GameObject { get; set; }
public Component() public Component()
{ {
+60 -15
View File
@@ -198,7 +198,7 @@ namespace Newtonsoft.Json.Bson
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
private bool IsWrappedInTypeObject() private bool IsWrappedInTypeObject()
@@ -219,7 +219,7 @@ namespace Newtonsoft.Json.Bson
} }
} }
throw new JsonReaderException("Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
} }
return false; return false;
@@ -233,18 +233,33 @@ namespace Newtonsoft.Json.Bson
{ {
Read(); Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float) if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float)
{ {
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture)); SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal)Value; return (decimal)Value;
} }
if (TokenType == JsonToken.Null)
return null;
decimal d;
if (TokenType == JsonToken.String)
{
if (decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
}
else
{
throw CreateReaderException(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
/// <summary> /// <summary>
@@ -260,13 +275,28 @@ namespace Newtonsoft.Json.Bson
SetToken(JsonToken.Float, Convert.ToInt32(Value, CultureInfo.InvariantCulture)); SetToken(JsonToken.Float, Convert.ToInt32(Value, CultureInfo.InvariantCulture));
return (int)Value; return (int)Value;
} }
if (TokenType == JsonToken.Null) if (TokenType == JsonToken.Null)
return null; return null;
int i;
if (TokenType == JsonToken.String)
{
if (int.TryParse((string)Value, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i);
return i;
}
else
{
throw CreateReaderException(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading integer. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading integer. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
#if !NET20 #if !NET20
@@ -280,18 +310,33 @@ namespace Newtonsoft.Json.Bson
{ {
Read(); Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date) if (TokenType == JsonToken.Date)
{ {
SetToken(JsonToken.Date, new DateTimeOffset((DateTime) Value)); SetToken(JsonToken.Date, new DateTimeOffset((DateTime) Value));
return (DateTimeOffset) Value; return (DateTimeOffset) Value;
} }
if (TokenType == JsonToken.Null)
return null;
DateTimeOffset dt;
if (TokenType == JsonToken.String)
{
if (DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.None, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw CreateReaderException(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
#endif #endif
@@ -320,7 +365,7 @@ namespace Newtonsoft.Json.Bson
case BsonReaderState.CodeWScopeScopeEnd: case BsonReaderState.CodeWScopeScopeEnd:
return ReadCodeWScope(); return ReadCodeWScope();
default: default:
throw new JsonReaderException("Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState)); throw CreateReaderException(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
} }
} }
catch (EndOfStreamException) catch (EndOfStreamException)
@@ -411,7 +456,7 @@ namespace Newtonsoft.Json.Bson
} }
else else
{ {
throw new JsonReaderException("Unexpected state when reading BSON reference: " + _bsonReaderState); throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
} }
} }
case State.PostValue: case State.PostValue:
@@ -430,11 +475,11 @@ namespace Newtonsoft.Json.Bson
} }
else else
{ {
throw new JsonReaderException("Unexpected state when reading BSON reference: " + _bsonReaderState); throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
} }
} }
default: default:
throw new JsonReaderException("Unexpected state when reading BSON reference: " + CurrentState); throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + CurrentState);
} }
} }
@@ -487,7 +532,7 @@ namespace Newtonsoft.Json.Bson
else if (context.Position == lengthMinusEnd) else if (context.Position == lengthMinusEnd)
{ {
if (ReadByte() != 0) if (ReadByte() != 0)
throw new JsonReaderException("Unexpected end of object byte value."); throw CreateReaderException(this, "Unexpected end of object byte value.");
PopContext(); PopContext();
if (_currentContext != null) if (_currentContext != null)
@@ -499,7 +544,7 @@ namespace Newtonsoft.Json.Bson
} }
else else
{ {
throw new JsonReaderException("Read past end of current container context."); throw CreateReaderException(this, "Read past end of current container context.");
} }
case State.ConstructorStart: case State.ConstructorStart:
break; break;
+12 -2
View File
@@ -103,6 +103,7 @@ namespace Newtonsoft.Json
internal State _currentState; internal State _currentState;
private JTokenType _currentTypeContext; private JTokenType _currentTypeContext;
private bool _serializerInArray; private bool _serializerInArray;
private CultureInfo _culture;
internal void SetSerializeInArray(bool serializerInArray) internal void SetSerializeInArray(bool serializerInArray)
{ {
@@ -181,6 +182,15 @@ namespace Newtonsoft.Json
} }
} }
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary> /// </summary>
@@ -473,7 +483,7 @@ namespace Newtonsoft.Json
int lineNumber; int lineNumber;
int linePosition; int linePosition;
if (lineInfo != null) if (lineInfo != null && lineInfo.HasLineInfo())
{ {
lineNumber = lineInfo.LineNumber; lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition; linePosition = lineInfo.LinePosition;
@@ -492,7 +502,7 @@ namespace Newtonsoft.Json
if (!message.EndsWith(".")) if (!message.EndsWith("."))
message += "."; message += ".";
if (lineInfo != null) if (lineInfo != null && lineInfo.HasLineInfo())
message += " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); message += " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
return message; return message;
+29 -20
View File
@@ -51,7 +51,6 @@ namespace Newtonsoft.Json
} }
private ReadType _readType; private ReadType _readType;
private CultureInfo _culture;
private readonly TextReader _reader; private readonly TextReader _reader;
@@ -64,15 +63,6 @@ namespace Newtonsoft.Json
private StringBuffer _buffer; private StringBuffer _buffer;
private StringReference _stringReference; private StringReference _stringReference;
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary> /// </summary>
@@ -394,8 +384,10 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.Null) if (TokenType == JsonToken.Null)
return null; return null;
if (TokenType == JsonToken.Bytes) if (TokenType == JsonToken.Bytes)
return (byte[])Value; return (byte[])Value;
if (TokenType == JsonToken.StartArray) if (TokenType == JsonToken.StartArray)
{ {
List<byte> data = new List<byte>(); List<byte> data = new List<byte>();
@@ -442,16 +434,24 @@ namespace Newtonsoft.Json
throw CreateReaderException(this, "Unexpected end when reading decimal."); throw CreateReaderException(this, "Unexpected end when reading decimal.");
} while (TokenType == JsonToken.Comment); } while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Float) if (TokenType == JsonToken.Float)
return (decimal?)Value; return (decimal?)Value;
if (TokenType == JsonToken.Null)
return null;
decimal d; decimal d;
if (TokenType == JsonToken.String && decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d)) if (TokenType == JsonToken.String)
{ {
SetToken(JsonToken.Float, d); if (decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d))
return d; {
SetToken(JsonToken.Float, d);
return d;
}
else
{
throw CreateReaderException(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
} }
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
@@ -476,6 +476,7 @@ namespace Newtonsoft.Json
if (TokenType == JsonToken.Integer) if (TokenType == JsonToken.Integer)
return (int?)Value; return (int?)Value;
if (TokenType == JsonToken.Null) if (TokenType == JsonToken.Null)
return null; return null;
@@ -514,16 +515,24 @@ namespace Newtonsoft.Json
throw CreateReaderException(this, "Unexpected end when reading date."); throw CreateReaderException(this, "Unexpected end when reading date.");
} while (TokenType == JsonToken.Comment); } while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date) if (TokenType == JsonToken.Date)
return (DateTimeOffset)Value; return (DateTimeOffset)Value;
if (TokenType == JsonToken.Null)
return null;
DateTimeOffset dt; DateTimeOffset dt;
if (TokenType == JsonToken.String && DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.None, out dt)) if (TokenType == JsonToken.String)
{ {
SetToken(JsonToken.Date, dt); if (DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.None, out dt))
return dt; {
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw CreateReaderException(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
} }
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
+54 -9
View File
@@ -62,7 +62,7 @@ namespace Newtonsoft.Json.Linq
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
private bool IsWrappedInTypeObject() private bool IsWrappedInTypeObject()
@@ -83,7 +83,7 @@ namespace Newtonsoft.Json.Linq
} }
} }
throw new JsonReaderException("Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
} }
return false; return false;
@@ -97,18 +97,33 @@ namespace Newtonsoft.Json.Linq
{ {
Read(); Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float) if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float)
{ {
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture)); SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal) Value; return (decimal) Value;
} }
if (TokenType == JsonToken.Null)
return null;
decimal d;
if (TokenType == JsonToken.String)
{
if (decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
}
else
{
throw CreateReaderException(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
/// <summary> /// <summary>
@@ -124,13 +139,28 @@ namespace Newtonsoft.Json.Linq
SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture)); SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture));
return (int)Value; return (int)Value;
} }
if (TokenType == JsonToken.Null) if (TokenType == JsonToken.Null)
return null; return null;
int i;
if (TokenType == JsonToken.String)
{
if (int.TryParse((string)Value, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i);
return i;
}
else
{
throw CreateReaderException(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading integer. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading integer. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
#if !NET20 #if !NET20
@@ -142,18 +172,33 @@ namespace Newtonsoft.Json.Linq
{ {
Read(); Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date) if (TokenType == JsonToken.Date)
{ {
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value)); SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value));
return (DateTimeOffset)Value; return (DateTimeOffset)Value;
} }
if (TokenType == JsonToken.Null)
return null;
DateTimeOffset dt;
if (TokenType == JsonToken.String)
{
if (DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.None, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
}
else
{
throw CreateReaderException(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (ReaderIsSerializerInArray()) if (ReaderIsSerializerInArray())
return null; return null;
throw new JsonReaderException("Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); throw CreateReaderException(this, "Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
} }
#endif #endif
@@ -83,9 +83,9 @@ using System.Security;
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("4.0.5.0")] [assembly: AssemblyVersion("4.0.7.0")]
#if !PocketPC #if !PocketPC
[assembly: AssemblyFileVersion("4.0.5.14519")] [assembly: AssemblyFileVersion("4.0.7.14524")]
#endif #endif
[assembly: CLSCompliant(true)] [assembly: CLSCompliant(true)]
@@ -285,13 +285,13 @@ namespace Newtonsoft.Json.Serialization
JsonObjectContract contract = new JsonObjectContract(objectType); JsonObjectContract contract = new JsonObjectContract(objectType);
InitializeContract(contract); InitializeContract(contract);
contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType); contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType);
contract.Properties.AddRange(CreateProperties(contract.UnderlyingType, contract.MemberSerialization)); contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization));
// check if a JsonConstructorAttribute has been defined and use that // check if a JsonConstructorAttribute has been defined and use that
if (objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(c => c.IsDefined(typeof(JsonConstructorAttribute), true))) if (contract.NonNullableUnderlyingType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(c => c.IsDefined(typeof(JsonConstructorAttribute), true)))
{ {
ConstructorInfo constructor = GetAttributeConstructor(objectType); ConstructorInfo constructor = GetAttributeConstructor(contract.NonNullableUnderlyingType);
if (constructor != null) if (constructor != null)
{ {
contract.OverrideConstructor = constructor; contract.OverrideConstructor = constructor;
@@ -300,7 +300,7 @@ namespace Newtonsoft.Json.Serialization
} }
else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic) else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic)
{ {
ConstructorInfo constructor = GetParametrizedConstructor(objectType); ConstructorInfo constructor = GetParametrizedConstructor(contract.NonNullableUnderlyingType);
if (constructor != null) if (constructor != null)
{ {
contract.ParametrizedConstructor = constructor; contract.ParametrizedConstructor = constructor;
@@ -184,12 +184,12 @@ namespace Newtonsoft.Json.Serialization
ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType"); ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType");
UnderlyingType = underlyingType; UnderlyingType = underlyingType;
CreatedType = underlyingType;
IsNullable = ReflectionUtils.IsNullable(underlyingType); IsNullable = ReflectionUtils.IsNullable(underlyingType);
NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType;
CreatedType = NonNullableUnderlyingType;
IsConvertable = typeof(IConvertible).IsAssignableFrom(NonNullableUnderlyingType); IsConvertable = typeof(IConvertible).IsAssignableFrom(NonNullableUnderlyingType);
if (NonNullableUnderlyingType == typeof(byte[])) if (NonNullableUnderlyingType == typeof(byte[]))