Created
September 13, 2018 20:12
-
-
Save diegodfsd/def53757024eb65631125b8fcf0e1375 to your computer and use it in GitHub Desktop.
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
public class InterfaceContractResolver : DefaultContractResolver | |
{ | |
private readonly Type[] _interfaceTypes; | |
private readonly ConcurrentDictionary<Type, Type> _typeToSerializeMap; | |
public InterfaceContractResolver(params Type[] interfaceTypes) | |
{ | |
_interfaceTypes = interfaceTypes; | |
_typeToSerializeMap = new ConcurrentDictionary<Type, Type>(); | |
} | |
protected override IList<JsonProperty> CreateProperties( | |
Type type, | |
MemberSerialization memberSerialization) | |
{ | |
var typeToSerialize = _typeToSerializeMap.GetOrAdd( | |
type, | |
t => _interfaceTypes.FirstOrDefault( | |
it => it.IsAssignableFrom(t)) ?? t); | |
return base.CreateProperties(typeToSerialize, memberSerialization); | |
} | |
} |
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
JobHelper.SetSerializerSettings(new JsonSerializerSettings | |
{ | |
ContractResolver = new InterfaceContractResolver(typeof(IThingable)) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment