There are MANY questions and some very good answers about using Json.NET to deserialize to an interface instead of a concrete class. A quick search of Stack Overflow will turn up lots of related results. That said, I do not believe any of the questions specifically address the use case of an array of interfaces. So I do not believe this is a duplicate question - if I have missed a post, please link to it.
Given an interface like this:
public interface IFoo
{
public string Bar { get; set; }
}
And 2 implementations like this:
public class Foo1 : IFoo
{
public string Bar { get; set; }
public bool Other1 { get; set; }
}
public class Foo2 : IFoo
{
public string Bar { get; set; }
public int Other2 { get; set; }
}
And finally a parent class:
public class Parent
{
public IFoo[] Foos { get; set; }
}
I would expect that I should be able to deserialize a JSON payload like this:
{
"Foos": [{
"$type": "Foo1, MyLibrary",
"Bar": "I am a Foo 1",
"Other1": true
}, {
"$type": "Foo2, MyLibrary",
"Bar": "I am a Foo 2",
"Other2": 999
}
]
}
using the following statement:
Parent parent = JsonConvert.DeserializeObject<Parent>(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto })
The result I am seeing is not an exception being thrown, but simply that parent.Foos
is null.
What am I missing?