Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell Nancy to serialize enums into strings

Tags:

c#

nancy

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?

like image 667
Endy Tjahjono Avatar asked Mar 14 '23 09:03

Endy Tjahjono


1 Answers

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

like image 140
TheCodeJunkie Avatar answered Mar 18 '23 19:03

TheCodeJunkie