Created
November 26, 2013 05:33
-
-
Save hyrmn/7653890 to your computer and use it in GitHub Desktop.
Json serializer / deserializer for Headspring Lab's Enumeration
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 EnumerationJsonConverter : JsonConverter | |
| { | |
| public override bool CanConvert(Type objectType) | |
| { | |
| return IsEnumeration(objectType); | |
| } | |
| public bool IsEnumeration(Type type) | |
| { | |
| if (type == null || type.BaseType == null || !type.BaseType.IsGenericType) return false; | |
| var baseType = type.BaseType; | |
| if (baseType.GenericTypeArguments.Count() == 1) | |
| { | |
| return (type.BaseType == typeof(Enumeration<>).MakeGenericType(baseType.GenericTypeArguments.ToArray())); | |
| } | |
| return (type.BaseType == typeof(Enumeration<,>).MakeGenericType(baseType.GenericTypeArguments.ToArray())); | |
| } | |
| public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
| { | |
| var type = value.GetType(); | |
| var enumValue = type.GetProperty("Value").GetValue(value); | |
| writer.WriteValue(enumValue); | |
| } | |
| public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
| { | |
| var parser = objectType.GetMethod("FromValue", BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); | |
| var enumerable = parser.Invoke(null, new[] { reader.Value }); | |
| return enumerable; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment