Last active
January 19, 2016 09:01
-
-
Save MeirionHughes/6a5de2ea6304b73fcdf0 to your computer and use it in GitHub Desktop.
Use DisplayNameAttribute value for exported $type when using Json.Net (DisplayNameSerializationBinder)
This file contains 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 DisplayNameSerializationBinder : DefaultSerializationBinder | |
{ | |
private Dictionary<string, Type> _nameToType; | |
private Dictionary<Type, string> _typeToName; | |
public DisplayNameSerializationBinder() | |
{ | |
var customDisplayNameTypes = | |
this.GetType() | |
.Assembly | |
//concat with references if desired | |
.GetTypes() | |
.Where(x => x | |
.GetCustomAttributes(false) | |
.Any(y => y is DisplayNameAttribute)); | |
_nameToType = customDisplayNameTypes.ToDictionary( | |
t => t.GetCustomAttributes(false).OfType<DisplayNameAttribute>().First().DisplayName, | |
t => t); | |
_typeToName = _nameToType.ToDictionary( | |
t => t.Value, | |
t => t.Key); | |
} | |
public override void BindToName(Type serializedType, out string assemblyName, out string typeName) | |
{ | |
if (false == _typeToName.ContainsKey(serializedType)) | |
{ | |
base.BindToName(serializedType, out assemblyName, out typeName); | |
return; | |
} | |
var name = _typeToName[serializedType]; | |
assemblyName = null; | |
typeName = name; | |
} | |
public override Type BindToType(string assemblyName, string typeName) | |
{ | |
if (_nameToType.ContainsKey(typeName)) | |
return _nameToType[typeName]; | |
return base.BindToType(assemblyName, typeName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
output: