Serialize C# Enum Definition to Json

后端 未结 2 1213
误落风尘
误落风尘 2021-02-18 14:43

Given the following in C#:

[Flags]
public enum MyFlags {
  None = 0,
  First = 1 << 0,
  Second = 1 << 1,
  Third = 1 << 2,
  Fourth = 1 <&l         


        
相关标签:
2条回答
  • 2021-02-18 15:13
    public static class EnumExtensions
    {
        public static string EnumToJson(this Type type)
        {
            if (!type.IsEnum)
                throw new InvalidOperationException("enum expected");
    
            var results =
                Enum.GetValues(type).Cast<object>()
                    .ToDictionary(enumValue => enumValue.ToString(), enumValue => (int) enumValue);
    
    
            return string.Format("{{ \"{0}\" : {1} }}", type.Name, Newtonsoft.Json.JsonConvert.SerializeObject(results));
    
        }
    }
    

    Using a dictionary of to do the heavy lifting. Then using Newtonsoft's json convert to convert that to json. I just had to do a bit of wrapping to add the type name on.

    0 讨论(0)
  • 2021-02-18 15:15

    You're better off populating a Dictionary<string,int> or a Typed DTO and serializing that.

    0 讨论(0)
提交回复
热议问题