Search code examples
c#jsonenumsservicestackjsonserializer

Custom Json Enum Serialization using ServiceStack


I'm trying to serialize enum in json. If Enum Value is "Male" and "Female". I want it as "M" and "F". Here is the code sample,it works for XmlSerializer but i need to make it work for JsonSerializer

public enum Gender
{
    [EnumMember(Value = "M"), XMLEnum("M")]
    Male,

    [EnumMember(Value = "F"), XMLEnum("F")]
    Female
}

P.S. I'm using ServiceStack as Json Serializer


Solution

  • An nice approach would be to use the SerializeFn routine of the ServiceStack configuration object, and configure your custom serialization for the Gender enum.

    var person = new Person()
    {
        FullName = "John Johnson",
        Gender = Gender.Male
    };
    
    JsConfig<Gender>.SerializeFn = c =>
        c.Equals(Gender.Male) ? "M" : "F";
    
    var result = person.ToJson(); // {"FullName":"John Johnson","Gender":"M"}
    

    Update: Since we determined you can't upgrade your ServiceStack.Text library to 4+, and you would definitely like to leverage the existing enummember attributes, here is a solution that skips the SerializeFn approach completely.

    You can install an additional nuget package called ServiceStack.Text.EnumMemberSerializer, which allows you to use the existing enummember attributes. Here is the code to make it work:

    new EnumSerializerConfigurator()
        .WithEnumTypes(new Type[] { typeof(Gender) })
        .Configure();
    
    JsConfig.Reset();
    
    var result = JsonSerializer.SerializeToString(person); // {"FullName":"John Johnson","Gender":"M"}
    

    I have tested with ServiceStack.Text 3.9 and it worked.