Skip to content

Exception it thrown during deserialization for generic base type #177

Open
@hankovich

Description

@hankovich

Source/destination types

abstract class Base<T>
{
	public T Value { get; set; }
	
	public abstract string Kind { get; }
}

class Nested1<T> : Base<T>
{
	public override string Kind => "1";
}

class Nested2<T>: Base<T>
{
	public override string Kind => "2";
}

Source/destination JSON

{"Kind":"1","Value":42}

Expected behavior

Deserialization succeeds

Actual behavior

An JsonSerializationException is thrown with message Could not create an instance of type Base1[System.Int32]. Type is an interface or abstract class and cannot be instantiated. Path 'Kind', line 1, position 8.`

Steps to reproduce

var settings = new JsonSerializerSettings();
settings.Converters.Add(JsonSubtypesConverterBuilder
	.Of(typeof(Base<>), "Kind") // type property is only defined here
	.RegisterSubtype(typeof(Nested1<>), "1")
	.RegisterSubtype(typeof(Nested2<>), "2")
	.SerializeDiscriminatorProperty() // ask to serialize the type property
	.Build());
	
var json = JsonConvert.SerializeObject(new Nested1<int>
{
	Value = 42,
}, settings); // {"Kind":"1","Value":42}

var @base = JsonConvert.DeserializeObject<Base<int>>(json, settings); // JsonSerializationException. Could not create an instance of type Base`1[System.Int32]. Type is an interface or abstract class and cannot be instantiated. Path 'Kind', line 1, position 8.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions