From 950b99ca1f45419b6ca51858ab77acfb69a2fd64 Mon Sep 17 00:00:00 2001 From: JamesNK Date: Sun, 2 Nov 2008 00:43:32 +0000 Subject: [PATCH] -Fix bug when deserializing to a nullable number --- .../JsonSerializerTest.cs | 40 +++++++++++++++++++ Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 3 ++ 2 files changed, 43 insertions(+) diff --git a/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs index ae81d4b3..2938d528 100644 --- a/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonSerializerTest.cs @@ -1431,5 +1431,45 @@ keyword such as type of business."" Assert.AreEqual("[1,2,3,4,5]", personRaw.RawContent.Content); Assert.AreEqual("LastNameValue", personRaw.LastName); } + + public class UserNullablle + { + public Guid Id; + public string FName; + public string LName; + public int RoleId; + public int? NullableRoleId; + public int? NullRoleId; + public bool? Active; + } + + [Test] + public void DeserializeNullableMember() + { + UserNullablle userNullablle = new UserNullablle + { + Id = new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), + FName = "FirstValue", + LName = "LastValue", + RoleId = 5, + NullableRoleId = 6, + NullRoleId = null, + Active = true + }; + + string json = JavaScriptConvert.SerializeObject(userNullablle); + + Assert.AreEqual(@"{""Id"":""ad6205e8-0df4-465d-aea6-8ba18e93a7e7"",""FName"":""FirstValue"",""LName"":""LastValue"",""RoleId"":5,""NullableRoleId"":6,""NullRoleId"":null,""Active"":true}", json); + + UserNullablle userNullablleDeserialized = JavaScriptConvert.DeserializeObject(json); + + Assert.AreEqual(new Guid("AD6205E8-0DF4-465d-AEA6-8BA18E93A7E7"), userNullablleDeserialized.Id); + Assert.AreEqual("FirstValue", userNullablleDeserialized.FName); + Assert.AreEqual("LastValue", userNullablleDeserialized.LName); + Assert.AreEqual(5, userNullablleDeserialized.RoleId); + Assert.AreEqual(6, userNullablleDeserialized.NullableRoleId); + Assert.AreEqual(null, userNullablleDeserialized.NullRoleId); + Assert.AreEqual(true, userNullablleDeserialized.Active); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 5b432318..d73c22cf 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -73,6 +73,9 @@ namespace Newtonsoft.Json.Utilities if (initialValue == null) throw new ArgumentNullException("initialValue"); + if (ReflectionUtils.IsNullableType(targetType)) + targetType = Nullable.GetUnderlyingType(targetType); + Type initialType = initialValue.GetType(); if (targetType == initialType)