Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exception it thrown during deserialization for generic base type #177

Open
hankovich opened this issue May 8, 2024 · 0 comments
Open

Exception it thrown during deserialization for generic base type #177

hankovich opened this issue May 8, 2024 · 0 comments

Comments

@hankovich
Copy link

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant