Enum converter

Aug 17, 2008 at 7:58 AM
I needed a jsonconverter for enums and thought id share what I made.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace JawTek.Web2Notify
{
    class EnumConverter<T> : JsonConverter where T : struct
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType)
        {
            string e = reader.Value.ToString();
            return Enum.Parse(typeof(T), e, true);
        }

        public override void WriteJson(JsonWriter writer, object value)
        {
            if (value is T)
            {
                T e = (T)value;
                writer.WriteValue(Convert.ToInt32(e));
            }
            else
            {
                throw new Exception("Unexpected value when converting enumeration.");
            }
        }
    }
}