Given these class definitions:
public class TypeConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => serializer.Serialize(writer, value);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => serializer.Deserialize<T>(reader);
}
public interface ISubStuff
{
string Item { get; set; }
}
public class SubStuff : ISubStuff
{
public string Item { get; set; }
}
public interface IMainStuff
{
Dictionary<string, ISubStuff> SubStuff { get; set; }
}
I am trying to use the TypeConverter class in method declaration for deserialization as below but it's NOT working:
public class MainStuff : IMainStuff
{
[JsonConverter(typeof(TypeConverter<Dictionary<string, SubStuff>>))]
public Dictionary<string, ISubStuff> SubStuff
{
get;
set;
}
}
The call below to deserialize the json causes an unable to cast object of type Dictionary<string, SubStuff> to Dictionary<string, ISubStuff>
exception.
var jsonText = "{ \"SubStuff\": { } }";
var deser = JsonConvert.DeserializeObject<MainStuff><jsonText);