Enum JSON converter.

In addition to the SingleOrArrayEnumConverter mentioned previously I’ve also created a version to translate enums to/from JSON using the name of the enum rather than it’s value as is the default.

	
class EnumConverter<T> : JsonConverter
{
	public override bool CanConvert(Type objectType)
	{
		return (objectType == typeof(T));
	}

	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		JToken token = JToken.Load(reader);

		return (T)Enum.Parse(typeof(T), token.ToObject<string>());
	}

	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		value = value.ToString();

		serializer.Serialize(writer, value);
	}

	public override bool CanWrite
	{
		get { return true; }
	}
}
	
Categories: Programming

Leave a Reply

Your email address will not be published. Required fields are marked *