How to configure ServiceStack.Text to use EnumMemb

2019-08-01 11:57发布

问题:

This is a follow up question to my earlier question about ServiceStack.Text and deserializing json to .Net enums. The answer to that question resolves how to get ServiceStack.Text to use .Net DataContract and EnumMember to map strings to enum values. Now I am trying to serialize the same enums to various formats and while json serialization is working in a round-trip way as expected, both csv and jsv conversion are ignoring the data contract. Is there a way to configure ServiceStack.Text (version 5.1.0, running on .Net Core 2.1) in a way so that the following code would produce the same result of all output types and so that the output would honor the defined data contract?

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)
        {
            var testEnum = TestEnum.EnumValue;

            Console.WriteLine($"To json: {testEnum.ToJson()}");
            Console.WriteLine($"To csv: {testEnum.ToCsv()}");
            Console.WriteLine($"To jsv: {testEnum.ToJsv()}");
            Console.WriteLine($"To xml: {testEnum.ToXml()}");
        }
    }
}

The actual output is

To json: "enum_value"
To csv: EnumValue
To jsv: EnumValue
To xml: <?xml version="1.0" encoding="utf-8"?><TestClass.TestEnum xmlns="http://schemas.datacontract.org/2004/07/TestNameSpace">enum_value</TestClass.TestEnum>

While I would like to see enum_value also in csv and jsv output. Is this possible with ServiceStack.Text?

回答1:

Should now be supported from this commit available from v5.1.1 that's now on MyGet.