SimpleJson: more informative exception when attempting to deserialize

object with non-empty constructor
This commit is contained in:
Zachary Becknell 2018-04-16 22:28:05 -04:00 committed by Steve Sanderson
parent 6c5f2a2262
commit a9dc626cbe
2 changed files with 30 additions and 1 deletions

View File

@ -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<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in SetCache[type])
{
object jsonValue;

View File

@ -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<InvalidOperationException>(() =>
{
JsonUtil.Deserialize<NonEmptyConstructorPoco>(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; }