如何将Enum定义转换为JavaScript对象(json)

时间:2019-09-30 11:26:13

标签: .net jsonserializer

我也检查了此post,但它给了我相同的结果。 枚举定义:

    public enum myEnum
        {
            variable1 = 1,
            variable2 = 25,
            variable3 = 35
        }

这是我尝试过的:

var myJsObject= @Html.Raw(JsonConvert.SerializeObject(Enum.GetValues(typeof(myEnum)), new Newtonsoft.Json.Converters.StringEnumConverter()));

这就是它的返回结果:

["variable1","variable2","variable3"]

预期结果:

{"1":"variable1","25":"variable2","35":"variable3",}

我该如何实现?

1 个答案:

答案 0 :(得分:1)

你可以这样子。

   public enum myEnum
   {
      variable1 = 1,
      variable2 = 25,
      variable3 = 35
   }

    static Dictionary<int,string> EnumToDictionary<T>() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an enum type");
        }
        var dictionary = Enum.GetValues(typeof(T))
            .Cast<T>()
            .ToDictionary( e=>  Convert.ToInt32(e), e => e.ToString());
        return dictionary;
    }

使用...

var dictionary =  EnumToDictionary<tEnum>();
var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);