I have some classes that model the structure I expect from my JSON file. For values that are an array in the JSON, the corresponding C# properties are declared to have the type IList<T> for various types T. I do not control these classes. When deserializing the JSON into the root type MyClass, how can I make it so that all properties of the classes that I get back of type IList<T> are constructed using the concrete type ObservableCollection<T>? Please note that MyClass has deeply nested properties of type IList<T>.
Hopefully the following example shows my intentions a bit more clearly:
class MyClass{
public IList<NestedClass> MyList { get; set; }
}
class NestedClass{
public IList<AnotherNestedClass> NestedList { get; set; }
}
class AnotherNestedClass{
// ... various properties.
}
var obj = JsonSerializer.Deserialize<MyClass>(jsonString);
Console.WriteLine(obj?.MyList?.GetType()); // This should be ObservableCollection<NestedClass>
You can use a custom
JsonConverterFactoryto automatically deserialize any properties or values declared asIList<T>to beObservableCollection<T>.First define the following converter factory:
Then deserialize using the following options:
Demo fiddle here.