Nancy by default serialize enums into integers when generating JSON response. I need to serialize enums into strings.
There is a way to customize Nancy's JSON serialization by creating JavaScriptPrimitiveConverter. For example this is what I did to customize serialization for ONE enum:
Create the customization class:
public class JsonConvertEnum : JavaScriptPrimitiveConverter
{
public override IEnumerable<Type> SupportedTypes
{
get
{
yield return typeof(MyFirstEnum);
}
}
public override object Deserialize(
object primitiveValue, Type type, JavaScriptSerializer serializer)
{
if (type == typeof(MyFirstEnum))
{
var serialized = (string)primitiveValue;
MyFirstEnum deserialized;
if (Enum.TryParse(serialized, out deserialized))
{
return deserialized;
}
else
{
return null;
}
}
return null;
}
public override object Serialize(
object obj, JavaScriptSerializer serializer)
{
if (obj is MyFirstEnum)
{
var deserialized = (MyFirstEnum)obj;
var serialized = deserialized.ToString();
return serialized;
}
return null;
}
}
Register it during bootstrap:
protected override void ApplicationStartup(
Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
Nancy.Json.JsonSettings.PrimitiveConverters.Add(new JsonConvertEnum());
}
I need to do this for ALL of my enums.
Is there a simpler way?
I haven't had the time to test it myself, but the following code should work for all Enum
types
public class JsonConvertEnum : JavaScriptPrimitiveConverter
{
public override IEnumerable<Type> SupportedTypes
{
get
{
yield return typeof(Enum);
}
}
public override object Deserialize(
object primitiveValue, Type type, JavaScriptSerializer serializer)
{
if (!type.IsEnum)
{
return null;
}
return Enum.Parse(type, (string)primitiveValue);
}
public override object Serialize(
object obj, JavaScriptSerializer serializer)
{
if (!obj.GetType().IsEnum)
{
return null;
}
return obj.ToString();
}
}
Basically it uses the Type
metadata to determine if it is an Enum
or not and then makes use of Enum.Parse(...)
to convert it from the primitive value back to the correct enum. To convert from Enum
to string
all you have to do is to cast the value to a string
It can be made more terse by using the ternary operator, but I left the more verbose version for clarity
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With