zoukankan      html  css  js  c++  java
  • 将 C# 枚举序列化为 JSON 字符串 基础理论

    Markdown

    该转换过程需要引用 Newtonsoft.JSON,这其中的转换过程还是蛮有意思的。

    一、定义枚举

    /// <summary>
    /// 托寄物品枚举
    /// </summary>
    public enum DeliveryGoodsEnum
    {
        文件 = 1,
        数码产品 = 2,
        生活用品 = 3,
        服饰 = 4,
        食品 = 5,
        其他 = 6
    }
    

    通常来说,这些值会绑定于类似下拉框这样的控件中,一个用于显示文本(text),一个则是值(value)。

    二、定义转换方法

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

    在以上转换过程中,枚举首先被转化为字典,接着才被序列化为字符串。

    三、转换成 JSON 字符串并组织起来发往客户端

    以 ASP.NET MVC 3 环境为例:

    // 托寄物品
    string deliveryGoodsEnumJson = typeof(DeliveryGoodsEnum).EnumToJson();
    // 付款方式
    string paymentModeEnumJson = typeof(PaymentModeEnum).EnumToJson();
    // 嘱咐
    string expectationEnumJson = typeof(ExpectationEnum).EnumToJson();
     
    result.Data = new
    {
        enumData = new Dictionary<string, object>()
        {
            { "deliveryGoods", deliveryGoodsEnumJson },
            { "paymentMode",   paymentModeEnumJson },
            { "expectation",   expectationEnumJson }
        }
    };
    return Json(result, JsonRequestBehavior.AllowGet);
    

    四、JS 提取枚举值并呈现

    var data = result.Data;
     
    // 托寄物品
    var deliveryGoods = $.parseJSON(data.enumData.deliveryGoods).DeliveryGoodsEnum;
     
    $ddlDeliveryGoods.empty();
    $.each(deliveryGoods, function (key, val) {
        console.log(key + ":" + val);
        $ddlDeliveryGoods.append("<li val='" + val + "'>" + key + "</li>");
    });
    

    通过 $.parseJSON() 转换为 JSON 对象,然后遍历枚举各项。

  • 相关阅读:
    LeetCode Flatten Binary Tree to Linked List
    LeetCode Longest Common Prefix
    LeetCode Trapping Rain Water
    LeetCode Add Binary
    LeetCode Subsets
    LeetCode Palindrome Number
    LeetCode Count and Say
    LeetCode Valid Parentheses
    LeetCode Length of Last Word
    LeetCode Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/ramantic/p/7606130.html
Copyright © 2011-2022 走看看