Created
April 7, 2015 23:10
-
-
Save teamaton/bba69cf95b9e6766f231 to your computer and use it in GitHub Desktop.
JSON.NET: ConcreteTypeConverter and ConcreteTypeListConverter classes for deserialization of interface properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks again for that tidbit ! It did the trick, as expected :-)