Search code examples
c#jsonjson.netdeserialization

Deserialise IList<Interface> in JSON.NET


I have some json that I want to Deserialise. It's very easy to deserialise back to an List However I am working with interfaces, and this is what I need the deserialisation to end up at:

So Let's start with some JSON:

[{"TimeGenerated":"2017-05-30T19:21:06.5331472+10:00","OuterValue":1.08,"Identifier":{"IdentifierName":"BLA","IdentifierNumber":1},"Locale":{"LocaleName":"LOCALE NAME","LocaleType":1,"LocaleNumber":1,"StartTime":"2017-05-30T19:20:00+10:00"},"InnerValue":1.08,"InnerType":0,"InnerId":"InnerI","Type":"MyType","Id":"11111"}]

This is the data that is Serialised on the server side (without issue of course) and it's object type is :

IList<IRootObject>

So effectively, I want to deserialise the other side as:

IList<IRootObject> MyDeserialisedObject = JsonConvert.Deserialise<IList<IRootObject>>(JsonString);

Obviously the pickle here is the old interface/abstract type error of:

'Could not create an instance of type BLA. Type is an interface or abstract class and cannot be instantiated'

Fine, I create some custom converters and decorate as follows:

Classes are:

    [JsonObject(MemberSerialization.OptIn)]
    public class Identifier
    {
        [JsonProperty]
        public string IdentifierName { get; set; }
        [JsonProperty]
        public int IdentifierNumber { get; set; }
    }
    [JsonObject(MemberSerialization.OptIn)]
    public class Locale
    {
        [JsonProperty]
        public string LocaleName { get; set; }
        [JsonProperty]            
        public int LocaleType { get; set; }
        [JsonProperty]            
        public int LocaleNumber { get; set; }
        [JsonProperty]
        public string StartTime { get; set; }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public class RootObject:IRootObject
    {
       [JsonProperty]
       public string TimeGenerated { get; set; }
       [JsonProperty]        
       public double OuterValue { get; set; }
       [JsonProperty] 
       [JsonConverter(typeof(ConcreteConverter<Identifier>))]
       public IIdentifier Identifier { get; set; }
       [JsonProperty]
       [JsonConverter(typeof(ConcreteConverter<Locale>))]
       public ILocale Locale { get; set; }
       [JsonProperty]
       public double InnerValue { get; set; }
       [JsonProperty]
       public int InnerType { get; set; }
       [JsonProperty]
       public string InnerId { get; set; }
       [JsonProperty]
       public string Type { get; set; }
       [JsonProperty]
       public string Id { get; set; }
    }

Interface is:

public interface IRootObject
{
    string TimeGenerated { get; set; }
    double OuterValue { get; set; }
    Identifier Identifier { get; set; }
    Locale Locale { get; set; }
    double InnerValue { get; set; }
    int InnerType { get; set; }
    string InnerId { get; set; }
    string Type { get; set; }
    string Id { get; set; }
}

Concrete Converter is as follows:

public class ConcreteConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    try
    {
        var s = serializer.Deserialize<T>(reader);
        return s;
    }
    catch (Exception ex)
    {
        return null;
    }
    // return serializer.Deserialize<T>(reader);
}

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

}

I also have a list converter which I have made (seeing this is a list albeit this is unused, but here JIC it is needed):

public class ConcreteListConverter<TInterface, TImplementation> : JsonConverter where TImplementation : TInterface
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    if (existingValue == null)
        return null;

    var res = serializer.Deserialize<List<TImplementation>>(reader);
    return res.ConvertAll(x => (TInterface)x);
}

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

}

}

So the issues are:

When I run:

IList<IRootObject> MyDeserialisedObject = JsonConvert.Deserialise<IList<IRootObject>>(JsonString);

I always get a null returned.

When i put breakpoints on my ConcreteConverter CanConvert/ReadJson/WriteJson methods - they are never hit.

What am I missing, and how do i get the magic of:

IList<IRootObject> MyDeserialisedObject = JsonConvert.Deserialise<IList<IRootObject>>(JsonString);

to work properly.

I must note, I DO NOT want to just typnamehandling.objects (i think this is it) where it adds the ASSEMBLYNAME.TYPE etc into the json, thus bloating it. Just assume that the json above is what we have to work with, and the classes represented above, with their interfaces is what it must be deserialised to.

Regards,

Chud

PS - I have changed the class names/properties etc away from the actual real world implementation of what I am doing. So if they have come out with an error, I do apologise. But hopefully the majority is all ok, and the point/ultimate goal is understood :)


Solution

  • The Problem

    You cannot create instances of an interface, that is not allowed in .NET. You cannot do this:

    var items = new IList<int>(); // Not allowed
    

    Your error is clearly stating that:

    Could not create an instance of type BLA. Type is an interface or abstract class and cannot be instantiated'

    The Solution

    Deserialize it to type List but assign it to type IList. Please note the types on the right side are not interfaces in code below except at the casting stage.

    IList<IRootObject> MyDeserialisedObject = 
                JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(JsonString))
                .Cast<IRootObject>().ToList();
    

    Some More Belabor

    You may ask "Why do I need to cast" and why can I not do this instead?

    IList<IRootObject> MyDeserialisedObject = 
                JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(JsonString));
    

    That is not allowed in order to preserve reference identity.