-Fixed empty strings not correctly deserializing as null onto nullable properties

This commit is contained in:
James Newton-King
2012-10-04 00:02:26 +13:00
parent e2a0191ee5
commit 382fb8df62
2 changed files with 56 additions and 5 deletions
@@ -2246,8 +2246,8 @@ Path '', line 1, position 2.",
[Test]
public void DeserializeEnsureTypeEmptyStringToIntError()
{
ExceptionAssert.Throws<JsonReaderException>(
@"Could not convert string to integer: . Path 'ReadTimeout', line 1, position 15.",
ExceptionAssert.Throws<JsonSerializationException>(
@"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 15.",
() =>
{
JsonConvert.DeserializeObject<MemoryStream>("{ReadTimeout:''}", new JsonSerializerSettings
@@ -7179,6 +7179,36 @@ Parameter name: value",
Assert.AreEqual("07/19/2012 14:30:00 +09:30", dateTimeOffset.ToString(CultureInfo.InvariantCulture));
}
#endif
#if !NET20
public class NullableTestClass
{
public bool? MyNullableBool { get; set; }
public int? MyNullableInteger { get; set; }
public DateTime? MyNullableDateTime { get; set; }
public DateTimeOffset? MyNullableDateTimeOffset { get; set; }
public Decimal? MyNullableDecimal { get; set; }
}
[Test]
public void TestStringToNullableDeserialization()
{
string json = @"{
""MyNullableBool"": """",
""MyNullableInteger"": """",
""MyNullableDateTime"": """",
""MyNullableDateTimeOffset"": """",
""MyNullableDecimal"": """"
}";
NullableTestClass c2 = JsonConvert.DeserializeObject<NullableTestClass>(json);
Assert.IsNull(c2.MyNullableBool);
Assert.IsNull(c2.MyNullableInteger);
Assert.IsNull(c2.MyNullableDateTime);
Assert.IsNull(c2.MyNullableDateTimeOffset);
Assert.IsNull(c2.MyNullableDecimal);
}
#endif
}
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
+24 -3
View File
@@ -388,7 +388,14 @@ namespace Newtonsoft.Json
DateTimeOffset dt;
if (TokenType == JsonToken.String)
{
if (DateTimeOffset.TryParse((string)Value, Culture, DateTimeStyles.RoundtripKind, out dt))
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt);
return dt;
@@ -500,7 +507,14 @@ namespace Newtonsoft.Json
decimal d;
if (TokenType == JsonToken.String)
{
if (decimal.TryParse((string)Value, NumberStyles.Number, Culture, out d))
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d);
return d;
@@ -544,7 +558,14 @@ namespace Newtonsoft.Json
int i;
if (TokenType == JsonToken.String)
{
if (int.TryParse((string)Value, NumberStyles.Integer, Culture, out i))
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i);
return i;