Search code examples
.netservicestackdatacontractservicestack-text

How to deserialize nullable enum with EnumMember attribute in ServiceStack.Text?


This is a follow up question to my these two earlier questions about ServiceStack.Text: first, second. As seen by checking answers to those questions, it is possible to serialize and deserialize enums based on their data contract's and EnumMember attributes. But what about nullable enumerations, i.e. EnumType? type. Using ServiceStack.Text, is it possible to serialize these using the EnumMember attribute? Using ServiceStack.Text 5.2.0, the following code:

namespace TestNameSpace
{
    using ServiceStack;
    using System;
    using System.Runtime.Serialization;

    class TestClass
    {
        [DataContract]
        enum TestEnum
        {
            [EnumMember(Value = "enum_value")]
            EnumValue = 0,
        }

        static void Main(string[] args)
        {
            TestEnum? nullableEnum = TestEnum.EnumValue;
            Console.WriteLine($"nullableEnum.ToJson: {nullableEnum.ToJson()}");
            Console.WriteLine($"nullableEnum.ToCsv: {nullableEnum.ToCsv()}");
            Console.WriteLine($"nullableEnum.ToJsv: {nullableEnum.ToJsv()}");
            Console.WriteLine($"nullableEnum.ToXml: {nullableEnum.ToXml()}");
        }
    }
}

prints the following:

nullableEnum.ToJson: "EnumValue"
nullableEnum.ToCsv: EnumValue
nullableEnum.ToJsv: EnumValue
nullableEnum.ToXml: <?xml version="1.0" encoding="utf-8"?><TestClass.TestEnum xmlns="http://schemas.datacontract.org/2004/07/TestNameSpace">enum_value</TestClass.TestEnum>

while I would expect all output formats to have enum_value. Is it possible achieve this with ServiceStack.Text?


Solution

  • Should now be resolved from this commit. This change is available from v5.2.1 that's now available on MyGet.