Deserialize into Dictionary<string, IMyInterface>

Nov 4, 2013 at 12:57 PM
Edited Nov 4, 2013 at 12:58 PM
Hello there,

You might be able to give me any better solution to get interface from properties annotated with a [JsonProperty].

For interfaces not located into collections, I have created a generic JsonConverter (see below). When a property with a specific interface is received it gives the appropriate JsonConverter. This is fine for me and I think that it is simple enough.

Here is my solution for changing an interface into a concrete type (working) :
public class MediaEntity : IMediaEntity
{
    [JsonProperty("sizes")]
    [JsonConverter(typeof(JsonObjectConverter<IMediaEntitySize, MediaEntitySize>))]
    public IMediaEntitySize Size { get; set; }
}

public class JsonObjectConverter<T, U> : JsonConverter 
    where U : T
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return serializer.Deserialize<U>(reader);
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof (T));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
Now my question is how to do this for a collection of interface?
I have read about the CustomCreationConverter but I cannot see how to implement this in my problem as I would like to use this in collection nested in other objects.
Also I am trying to use mostly use annotation to automate the conversion.

Here is what I would like to achieve :
  • Define a converter between an interface and a concrete type (as shown above).
  • When a collection of the interface is detected change each type into the appropriate concrete type.
public class MediaEntity : IMediaEntity
{
    [JsonProperty("sizes")]
    [JsonConverter(typeof(JsonObjectConverter<IMediaEntitySize, MediaEntitySize>))]
    public Dictionary<string, IMediaEntitySize> Sizes { get; set; }
}
Thank you in advance for your time.
Linvi
May 26, 2014 at 4:39 PM
First , thanks for your JsonObjectConverter, base of this class , I solve my problem about interface collection .
And, for your question, very simple:
            JsonSerializerSettings = new JsonSerializerSettings
            {
                Converters = new JsonConverter[]
                {
                    new JsonObjectConverter<IYourInterface,YourImplement>(),
                },
            };
Other, I tried Binder to resolve implement type name ,but I don't know why binder code don't run .