Tuesday, November 02, 2010

Serialising Enums with Newtonsoft JSON.Net

For a while... I was using this serializer:

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

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

public override object ReadJson(JsonReader reader, Type
objectType, object existingValue, JsonSerializer serializer)
{
return Enum.Parse(typeof(T), reader.Value.ToString());
}
}

This allowed me to serialize/deserialize using attributes like:

[JsonObject]
public class MyClass
{
[JsonConverter(typeof(SerializationUtils.JsonEnumConverter<DateTimeTestFormat>))]
public DateTimeTestFormat DateTimeTestFormat { get; set; }
}

However, eventually I worked out that I could just use a more general
solution - and that I could pass that in to the top-level JsonConvert
methods:

public class GeneralJsonEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsEnum;
}

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

public override object ReadJson(JsonReader reader, Type
objectType, object existingValue, JsonSerializer serializer)
{
return Enum.Parse(objectType, reader.Value.ToString());
}
}

Much easier... :)

No comments:

Post a Comment