zoukankan      html  css  js  c++  java
  • DataTable 的 JSON 序列化

    随着AJAX,MVC等WEB框架的使用,JavaScript又更多的回到了我们身边。
    在JS中我们需要对对象进行JSON序列化通常使用JSON.net , 不过它对DataTable的序列化不能很好的满足的我们的需求,后来在CodeProject发现一个兄弟已经写好了 Convert ASP.NET DataTable to JSON, to use datatable in JAVASCRIPT ,记一下,免得忘记了。

    public string CreateJsonParameters(DataTable dt)
    {
        /* /****************************************************************************
         * Without goingin to the depth of the functioning of this Method, i will try to give an overview
         * As soon as this method gets a DataTable it starts to convert it into JSON String,
         * it takes each row and in each row it grabs the cell name and its data.
         * This kind of JSON is very usefull when developer have to have Column name of the .
         * Values Can be Access on clien in this way. OBJ.HEAD[0].<ColumnName>
         * NOTE: One negative point. by this method user will not be able to call any cell by its index.
         * *************************************************************************/
        StringBuilder JsonString = new StringBuilder();
        //Exception Handling        
        if (dt != null && dt.Rows.Count > 0)
        {
        JsonString.Append("{ ");
        JsonString.Append("/"Head/":[ ");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            JsonString.Append("{ ");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
            if (j < dt.Columns.Count - 1)
            {
                JsonString.Append("/"" + dt.Columns[j].ColumnName.ToString() + "/":" + "/"" + dt.Rows[i][j].ToString() + "/",");
            }
            else if (j == dt.Columns.Count - 1)
            {
                JsonString.Append("/"" + dt.Columns[j].ColumnName.ToString() + "/":" + "/"" + dt.Rows[i][j].ToString() + "/"");
            }
            }
            /*end Of String*/
            if (i == dt.Rows.Count - 1)
            {
            JsonString.Append("} ");
            }
            else
            {
            JsonString.Append("}, ");
            }
        }
        JsonString.Append("]}");
        return JsonString.ToString();
        }
        else
        {
        return null;
    }
  • 相关阅读:
    bus总线
    vue 动态组件、父子组件传参
    echarts
    记录板
    留言板
    如何移除双系统mac中的windows系统
    Kernel,Shell,Bash 的关系
    zju 校队选拔 被虐记
    COGS 2638. 数列操作ψ 线段树
    退役公告【现已复活】
  • 原文地址:https://www.cnblogs.com/marslin/p/3112431.html
Copyright © 2011-2022 走看看