diff --git a/src/JSONParser.cs b/src/JSONParser.cs index 9db9821..8086984 100644 --- a/src/JSONParser.cs +++ b/src/JSONParser.cs @@ -128,9 +128,13 @@ static List Split(string json) internal static object ParseValue(Type type, string json) { if (type == typeof(string)) - { + { + if (json == "null") + return null; + if (json.Length <= 2) return string.Empty; + StringBuilder parseStringBuilder = new StringBuilder(json.Length); for (int i = 1; i < json.Length - 1; ++i) { @@ -198,6 +202,11 @@ internal static object ParseValue(Type type, string json) newArray.SetValue(ParseValue(arrayType, elems[i]), i); splitArrayPool.Push(elems); return newArray; + } + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + Type underlyingType = type.GetGenericArguments()[0]; + return ParseValue(underlyingType, json); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { diff --git a/test/TestParser.cs b/test/TestParser.cs index 14b7319..7eebacf 100644 --- a/test/TestParser.cs +++ b/test/TestParser.cs @@ -439,5 +439,57 @@ public void TestDuplicateKeysInAnonymousObject() */ Assert.AreEqual(dictionary["hello"], "hell", "The parser stored an incorrect value for the duplicated key"); } + + private class SimpleModelWithNulls + { + public string AString { get; set; } + public int? NullableInt { get; set; } + public float? NullableFloat { get; set; } + } + + [TestMethod] + public void FromJson_NullString_IsParsedCorrectly() + { + // Arrange + var json = "{\"AString\": null}"; + + // Act + var actual = json.FromJson(); + + // Assert + Assert.IsNull(actual.AString); + } + + [DataTestMethod] + [DataRow(null)] + [DataRow(5)] + [DataRow(-1)] + public void FromJson_NullableInt_IsParsedCorrectly(int? value) + { + // Arrange + var json = "{\"NullableInt\": " + (value?.ToString() ?? "null") + "}"; + + // Act + var actual = json.FromJson(); + + // Assert + Assert.AreEqual(value, actual.NullableInt); + } + + [DataTestMethod] + [DataRow(null)] + [DataRow(3.0f)] + [DataRow(2.5f)] + public void FromJson_NullableFloat_IsParsedCorrectly(float? value) + { + // Arrange + var json = "{\"NullableFloat\": " + (value?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "null") + "}"; + + // Act + var actual = json.FromJson(); + + // Assert + Assert.AreEqual(value, actual.NullableFloat); + } } }