Type is an interface or abstract class and cannot be instantiated

You’ll need to provide a custom serializer to Json.Net to tell it how to handle the child cogs. For example:

var settings = new JsonSerializerSettings();
settings.Converters.Add(new CogConverter());

Your CogConverter will need to inherit from JsonConverter and specify that it CanConvert your ICog interface. Perhaps something along the lines of:

public class CogConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ICog);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return serializer.Deserialize(reader, typeof(Cog));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

I’d recommend registering your JsonSerializerSettings with your IoC container in that case. You may want to consider giving CogConverter access to the container, too, if the serializer can’t be responsible for actually constructing the Cog itself; that all depends on your particular architecture.

Edit

Upon further reading, it seems like you might be looking for specifically how to use the IoC created ICog for population. I’m using the following as part of my ReadJson:

var target = serializer.Deserialize<Newtonsoft.Json.Linq.JObject>(reader);
var objectType = DetermineConcreteType(target);
var result = iocContainer.Resolve(objectType);
serializer.Populate(target.CreateReader(), result);
return result;

This allows you to use ANY object and populate it from the original JSON, using custom types as you wish inside your DetermineConcreteType method.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)