将C#枚举定义序列化为Json

Gav*_*aux 22 c# enums serialization json servicestack

在C#中给出以下内容:

[Flags]
public enum MyFlags {
  None = 0,
  First = 1 << 0,
  Second = 1 << 1,
  Third = 1 << 2,
  Fourth = 1 << 3
}  
Run Code Online (Sandbox Code Playgroud)

是否有任何现有方法ServiceStack.Text用于序列化到以下JSON?

{
  "MyFlags": {
    "None": 0,
    "First": 1,
    "Second": 2,
    "Third": 4,
    "Fourth": 8
  }
}
Run Code Online (Sandbox Code Playgroud)

目前我正在使用下面的例程,有没有更好的方法来做到这一点?

public static string ToJson(this Type type)
    {
        var stringBuilder = new StringBuilder();
        Array values = Enum.GetValues(type);
        stringBuilder.Append(string.Format(@"{{ ""{0}"": {{", type.Name));

        foreach (Enum value in values)
        {
            stringBuilder.Append(
                string.Format(
                    @"""{0}"": {1},", 
                    Enum.GetName(typeof(Highlights), value), 
                    Convert.ChangeType(value, value.GetTypeCode())));
        }

        stringBuilder.Remove(stringBuilder.Length - 1, 1);
        stringBuilder.Append("}}");
        return stringBuilder.ToString();
    }
Run Code Online (Sandbox Code Playgroud)

Kev*_*tch 7

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));

    }
}
Run Code Online (Sandbox Code Playgroud)

用字典来做繁重的工作.然后使用Newtonsoft的json转换将其转换为json.我只需要做一些包装就可以添加类型名称了.


myt*_*thz 6

你最好填充一个Dictionary<string,int>或一个Typed DTO并序列化它.