Skip to content

Instantly share code, notes, and snippets.

@teamaton
Created April 7, 2015 23:10
Show Gist options
  • Save teamaton/bba69cf95b9e6766f231 to your computer and use it in GitHub Desktop.
Save teamaton/bba69cf95b9e6766f231 to your computer and use it in GitHub Desktop.
JSON.NET: ConcreteTypeConverter and ConcreteTypeListConverter classes for deserialization of interface properties
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class ConcreteTypeConverter<TConcrete> : JsonConverter {
public override bool CanConvert(Type objectType) {
//this method is *not* called when using the JsonConverterAttribute to assign a converter
return objectType.IsAssignableFrom(typeof (TConcrete));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer) {
//explicitly specify the concrete type we want to create
return serializer.Deserialize<TConcrete>(reader);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
//use the default serialization - it works fine
serializer.Serialize(writer, value);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class ConcreteTypeListConverter<TInterface, TItem> : JsonConverter where TItem : TInterface {
public override bool CanConvert(Type objectType) {
//this method is *not* called when using the JsonConverterAttribute to assign a converter
return IsIList(objectType) || objectType.GetInterfaces().Any(IsIList);
}
private static bool IsIList(Type objectType) {
return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof (IList<>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer) {
//explicitly specify the concrete type we want to create
var specializedList = serializer.Deserialize<List<TItem>>(reader);
return specializedList.Cast<TInterface>().ToList();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
//use the default serialization - it works fine
serializer.Serialize(writer, value);
}
}
@dominicmarchand
Copy link

Thanks again for that tidbit ! It did the trick, as expected :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment