JavaScriptSerializer - JSON serialization of enum as string

后端 未结 27 1691
耶瑟儿~
耶瑟儿~ 2020-11-22 03:22

I have a class that contains an enum property, and upon serializing the object using JavaScriptSerializer, my json result contains the integer valu

27条回答
  •  终归单人心
    2020-11-22 04:12

    Here is a simple solution that serializes a server-side C# enum to JSON and uses the result to populate a client-side drop-down.

    Here goes:

    Example Enum

    public enum Role
    {
        None = Permission.None,
        Guest = Permission.Browse,
        Reader = Permission.Browse| Permission.Help ,
        Manager = Permission.Browse | Permission.Help | Permission.Customise
    }
    

    A complex enum that uses bitwise ORs to generate a permissions system. So you can't rely on the simple index [0,1,2..] for the integer value of the enum.

    Server Side - C#

    Get["/roles"] = _ =>
    {
        var type = typeof(Role);
        var data = Enum
            .GetNames(type)
            .Select(name => new 
                {
                    Id = (int)Enum.Parse(type, name), 
                    Name = name 
                })
            .ToArray();
    
        return Response.AsJson(data);
    };
    

    The code above uses the NancyFX framework to handle the Get request. It uses Nancy's Response.AsJson() helper method - but don't worry, you can use any standard JSON formatter as the enum has already been projected into a simple anonymous type ready for serialization.

    Generated JSON

    [
        {"Id":0,"Name":"None"},
        {"Id":2097155,"Name":"Guest"},
        {"Id":2916367,"Name":"Reader"},
        {"Id":4186095,"Name":"Manager"}
    ]
    

    Client Side - CoffeeScript

    fillSelect=(id, url, selectedValue=0)->
        $select = $ id
        $option = (item)-> $ "

    HTML Before

    
    

    HTML After

    
    

提交回复
热议问题