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; }