From a9dc626cbed549cb80af193551085d4fad44f388 Mon Sep 17 00:00:00 2001 From: Zachary Becknell Date: Mon, 16 Apr 2018 22:28:05 -0400 Subject: [PATCH] SimpleJson: more informative exception when attempting to deserialize object with non-empty constructor --- .../Json/SimpleJson/SimpleJson.cs | 5 +++- .../JsonUtilTest.cs | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNetCore.Blazor/Json/SimpleJson/SimpleJson.cs b/src/Microsoft.AspNetCore.Blazor/Json/SimpleJson/SimpleJson.cs index da3c82ef22..44eaa1d585 100644 --- a/src/Microsoft.AspNetCore.Blazor/Json/SimpleJson/SimpleJson.cs +++ b/src/Microsoft.AspNetCore.Blazor/Json/SimpleJson/SimpleJson.cs @@ -1430,7 +1430,10 @@ namespace SimpleJson obj = value; else { - obj = ConstructorCache[type](); + var constructorDelegate = ConstructorCache[type] + ?? throw new InvalidOperationException($"Cannot deserialize JSON into type '{type.FullName}' because it does not have a public parameterless constructor."); + obj = constructorDelegate(); + foreach (KeyValuePair> setter in SetCache[type]) { object jsonValue; diff --git a/test/Microsoft.AspNetCore.Blazor.Test/JsonUtilTest.cs b/test/Microsoft.AspNetCore.Blazor.Test/JsonUtilTest.cs index a0dd701b05..33115400a7 100644 --- a/test/Microsoft.AspNetCore.Blazor.Test/JsonUtilTest.cs +++ b/test/Microsoft.AspNetCore.Blazor.Test/JsonUtilTest.cs @@ -113,6 +113,32 @@ namespace Microsoft.AspNetCore.Blazor.Test Assert.Equal(1, simpleError.NullableIntProperty); } + [Fact] + public void NonEmptyConstructorThrowsUsefulException() + { + // Arrange + var json = "{\"Property\":1}"; + var type = typeof(NonEmptyConstructorPoco); + + // Act + var exception = Assert.Throws(() => + { + JsonUtil.Deserialize(json); + }); + + // Assert + Assert.Equal( + $"Cannot deserialize JSON into type '{type.FullName}' because it does not have a public parameterless constructor.", + exception.Message); + } + + class NonEmptyConstructorPoco + { + public NonEmptyConstructorPoco(int parameter) {} + + public int Property { get; set; } + } + struct SimpleStruct { public string StringProperty { get; set; }