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.

public 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; }
	}
}

This can then be used to decorate your enum class like so.

public class Alert
{
	[JsonConverter(typeof(EnumConverter<AlertType>))]
	public AlertType AlertType { get; set; }

	public string Message { get; set; }
}
Categories: Programming

0 Comments

Leave a Reply

Avatar placeholder

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