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

how to convert Enum definition to JavaScript object (json)

我也检查了这个 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()));

这就是它 returns:

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

预期结果:

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

我怎样才能做到这一点?

你可以这样..

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