Single or array enum JSON converter.

In addition to the SingleOrArrayConverter 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 SingleOrArrayEnumConverter<T> : JsonConverter
{
	public override bool CanConvert(Type objectType)
	{
		return (objectType == typeof(List<T>));
	}

	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		JToken token = JToken.Load(reader);
		if (token.Type == JTokenType.Array)
		{
			return token.ToObject<List<string>>().Select(x => (T)Enum.Parse(typeof(T), x.ToLower())).ToList();
		}
		
		return new List<T> { (T)Enum.Parse(typeof(T), token.ToObject<string>().ToLower()) };
	}

	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		if (value.GetType() == typeof(List<T>))
		{
			List<T> list = (List<T>)value;
			value = list.Select(x => x.ToString().ToLower()).ToList();
		}
		else if (value.GetType() == typeof(T))
		{
			value = value.ToString().ToLower();
		}

		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 *