How to configure ServiceStack.Text to use EnumMember when deserializing?

孤街浪徒 提交于 2019-12-04 05:29:04

问题


I am using ServiceStack.Text to deserialize json received in rest api calls to objects C#. The model classes I use have defined the string representation using EnumMember attributes. The problem is that ServiceStack.Text does not seem to use those values. ServiceStack.Text documentation has a section called Custom enum serialization that discusses EnumMember attribute, but it talks only about serialization with no mention of deserialization.

It is possible to configure ServiceStack.Text to use EnumMember when deserializing enums?

The following is an example of the situation:

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

    class TestClass
    {
        enum TestEnum
        {
            [EnumMember(Value = "default_value")]
            DefaultValue = 0,

            [EnumMember(Value = "real_value")]
            RealValue = 1
        }

        class TestEnumWrapper
        {
            public TestEnum EnumProperty { get; set; }

            public override string ToString()
            {
                return $"EnumProperty: {EnumProperty}";
            }
        }

        static void Main(string[] args)
        {
            string json = @"{ ""enumProperty"": ""real_value"" }";

            TestEnumWrapper deserialized =
                ServiceStack.Text.JsonSerializer.DeserializeFromString<TestEnumWrapper>(json);

            Console.WriteLine($"Deserialized: {deserialized}");
           // Prints: "Deserialized: EnumProperty: DefaultValue"
           // Expected: "Deserialized: EnumProperty: RealValue"
        }
    }
}

回答1:


I found out why my deserialization was not working. ServiceStack.Text was not interpreting the EnumMember attributes because enum declaration does not have DataContract attribute set. This is actually explained in the EnumMember documentation link I also linked in the question:

One way to use enumeration types in the data contract model is to apply the DataContractAttribute attribute to the type. You must then apply the EnumMemberAttribute attribute to each member that must be included in the data contract.

Expected results were produced by adding the missing attribute:

[DataContract] // This was missing
enum TestEnum
{ 
    // ...
}



回答2:


Support for [EnumMember] was only added during this release so you'll need to upgrade to v5.1.1 pre-release NuGet packages on MyGet.



来源:https://stackoverflow.com/questions/51854666/how-to-configure-servicestack-text-to-use-enummember-when-deserializing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!