C#中把Datatable转换为Json的5个代码实例

实例一:

代码如下:

/// <summary>    
    /// Datatable转换为Json    
    /// </summary>   
    /// <param name="table">Datatable对象</param>    
    /// <returns>Json字符串</returns>    
    public static string ToJson(DataTable dt)
    {
        StringBuilder jsonString = new StringBuilder();
        jsonString.Append("[");
        DataRowCollection drc = dt.Rows;
        for (int i = 0; i < drc.Count; i++)
        {
            jsonString.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                string strKey = dt.Columns[j].ColumnName;
                string strValue = drc[i][j].ToString();
                Type type = dt.Columns[j].DataType;
                jsonString.Append("\"" + strKey + "\":");
                strValue = StringFormat(strValue, type);
                if (j < dt.Columns.Count - 1)
                {
                    jsonString.Append(strValue + ",");
                }
                else
                {
                    jsonString.Append(strValue);
                }
            }
            jsonString.Append("},");
        }
        jsonString.Remove(jsonString.Length - 1, 1);
        jsonString.Append("]");
        return jsonString.ToString();
    }
    /// <summary>
    /// 格式化字符型、日期型、布尔型
    /// </summary>
    /// <param name="str"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    private static string StringFormat(string str, Type type)
    {
        if (type == typeof(string))
        {
            str = String2Json(str);
            str = "\"" + str + "\"";
        }
        else if (type == typeof(DateTime))
        {
            str = "\"" + str + "\"";
        }
        else if (type == typeof(bool))
        {
            str = str.ToLower();
        }
        else if (type != typeof(string) && string.IsNullOrEmpty(str))
        {
            str = "\"" + str + "\"";
        }
        return str;
    }
    /// <summary>
    /// 过滤特殊字符
    /// </summary>
    /// <param name="s">字符串</param>
    /// <returns>json字符串</returns>
    private static string String2Json(String s)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.Length; i++)
        {
            char c = s.ToCharArray()[i];
            switch (c)
            {
                case '\"':
                    sb.Append("\\\""); break;
                case '\\':
                    sb.Append("\\\\"); break;
                case '/':
                    sb.Append("\\/"); break;
                case '\b':
                    sb.Append("\\b"); break;
                case '\f':
                    sb.Append("\\f"); break;
                case '\n':
                    sb.Append("\\n"); break;
                case '\r':
                    sb.Append("\\r"); break;
                case '\t':
                    sb.Append("\\t"); break;
                default:
                    sb.Append(c); break;
            }
        }
        return sb.ToString();
    }

实例二:
 

代码如下:

public static 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("\"T_blog\":[ ");
                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;
            }
        }

效果:
{"T_blog":
  [
   {"id":"14","title":"北京奥运开幕式","addtime":"2008-08-08"},
   {"id":"15","title":"网络文化","addtime":"2008-09-12"},
   {"id":"17","title":"北京下雨了","addtime":"2008-09-19"},
   {"id":"21","title":"深圳地铁通了","addtime":"2008-09-25"}
  ]
}

实例三:

代码如下:

/// <summary>
    /// 将一个数据表转换成一个JSON字符串,在客户端可以直接转换成二维数组。
    /// </summary>
    /// <param name="source">需要转换的表。</param>
    /// <returns></returns>
    public static string DataTableToJson(DataTable source)
    {
        if (source.Rows.Count == 0)
            return "";
        StringBuilder sb = new StringBuilder("[");
        foreach (DataRow row in source.Rows)
        {
            sb.Append("[");
            for (int i = 0; i < source.Columns.Count; i++)
            {
                sb.Append('"' + row[i].ToString() + "\",");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("],");
        }
        sb.Remove(sb.Length - 1, 1);
        sb.Append("]");
        return sb.ToString();
    }

/// <summary>
    /// 反回JSON数据到前台
    /// </summary>
    /// <param name="dt">数据表</param>
    /// <returns>JSON字符串</returns>
    public string CreateJsonParameters(DataTable dt)
    {
        StringBuilder JsonString = new StringBuilder();
        //Exception Handling       
        if (dt != null && dt.Rows.Count > 0)
        {
            JsonString.Append("{ ");
            JsonString.Append("\"TableInfo\":[ ");
            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;
        }
    }

实例四:

代码如下:

public class DataTableConvertJson
    {

#region dataTable转换成Json格式
        /// <summary> 
        /// dataTable转换成Json格式 
        /// </summary> 
        /// <param name="dt"></param> 
        /// <returns></returns> 
        public static string DataTable2Json(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName);
            jsonBuilder.Append("\":[");
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

#endregion dataTable转换成Json格式
        #region DataSet转换成Json格式
        /// <summary> 
        /// DataSet转换成Json格式 
        /// </summary> 
        /// <param name="ds">DataSet</param>
        /// <returns></returns> 
        public static string Dataset2Json(DataSet ds)
        {
            StringBuilder json = new StringBuilder();

foreach (DataTable dt in ds.Tables)
            {
                json.Append("{\"");
                json.Append(dt.TableName);
                json.Append("\":");
                json.Append(DataTable2Json(dt));
                json.Append("}");
            } return json.ToString();
        }
        #endregion

/// <summary>
        /// Msdn
        /// </summary>
        /// <param name="jsonName"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJson(string jsonName, DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
    }

实例五:

代码如下:

#region  DataTable 转换为Json字符串实例方法
/// <summary>
/// GetClassTypeJosn 的摘要说明
/// </summary>
public class GetClassTypeJosn : IHttpHandler
{
    /// <summary>
    /// 文件名:DataTable 和Json 字符串互转
    /// 版权所有:Copyright (C) Create Family Wealth liangjw
    /// 创建标示:2013-08-03
    /// </summary>
    //用法说明实例
     public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        context.Response.Charset = "utf-8";
        HttpRequest req = context.Request;
        string method = req["method"].ToStr().ToLower();

//获取合同明细列表  DataTable 转换为Json字符串
        if (method == "txtdate")
        {
            string json = "";
            BO.MakeContractMx bll = new MakeContractMx();
            DataSet ds = bll.GetDataTable();
            if (ds.Tables.Count > 0)
            {
                json =ToJson(ds.Tables[0]);
            }
            context.Response.Write(json);
            return;
        }

}

public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

#endregion

#region Json字符串转换为DataTable 实例方法

public DataTable JsonToDataTable(json)
    {
       DataTable  dt= ToDataTable(json);
         return dt;
    }
   
   #endregion

#region DataTable 转换为Json 字符串
    /// <summary>
    /// DataTable 对象 转换为Json 字符串
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string ToJson(this DataTable dt)
    {
        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
        ArrayList arrayList = new ArrayList();
        foreach (DataRow dataRow in dt.Rows)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
            foreach (DataColumn dataColumn in dt.Columns)
            {
                dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
            }
            arrayList.Add(dictionary); //ArrayList集合中添加键值
        }

return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
    }
    #endregion

#region Json 字符串 转换为 DataTable数据集合
    /// <summary>
    /// Json 字符串 转换为 DataTable数据集合
    /// </summary>
    /// <param name="json"></param>
    /// <returns></returns>
    public static DataTable ToDataTable(this string json)
    {
        DataTable dataTable = new DataTable();  //实例化
        DataTable result;
        try
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
            if (arrayList.Count > 0)
            {
                foreach (Dictionary<string, object> dictionary in arrayList)
                {
                    if (dictionary.Keys.Count<string>() == 0)
                    {
                        result = dataTable;
                        return result;
                    }
                    if (dataTable.Columns.Count == 0)
                    {
                        foreach (string current in dictionary.Keys)
                        {
                            dataTable.Columns.Add(current, dictionary[current].GetType());
                        }
                    }
                    DataRow dataRow = dataTable.NewRow();
                    foreach (string current in dictionary.Keys)
                    {
                        dataRow[current] = dictionary[current];
                    }

dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                }
            }
        }
        catch
        {
        }
        result = dataTable;
        return result;
    }
    #endregion

#region 转换为string字符串类型
    /// <summary>
    ///  转换为string字符串类型
    /// </summary>
    /// <param name="s">获取需要转换的值</param>
    /// <param name="format">需要格式化的位数</param>
    /// <returns>返回一个新的字符串</returns>
    public static string ToStr(this object s, string format = "")
    {
        string result = "";
        try
        {
            if (format == "")
            {
                result = s.ToString();
            }
            else
            {
                result = string.Format("{0:" + format + "}", s);
            }
        }
        catch
        {
        }
        return result;
    }
   #endregion

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:

http://tools.jb51.net/code/json_yasuo_trans

C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json

(0)

相关推荐

  • C#实现String类型和json之间的相互转换功能示例

    本文实例讲述了C#实现String类型和json之间的相互转换功能.分享给大家供大家参考,具体如下: ////Donet2.0 需要添加引用 // 从一个对象信息生成Json串 public static string ObjectToJson(object obj) { return JavaScriptConvert.SerializeObject(obj); } // 从一个Json串生成对象信息 public static object JsonToObject(string jsonS

  • C#实现任意数据类型转成json格式输出

    直接贴代码: 复制代码 代码如下: /// List转成json   /// </summary>  /// <typeparam name="T"></typeparam>  /// <param name="jsonName"></param>  /// <param name="list"></param>  /// <returns></

  • C# XML与Json之间相互转换实例详解

    对于这转换其实很简单,其中最重要的就是先要引用类库.可以到官网进行下载引用http://json.codeplex.com. XML转换为Json字符串 复制代码 代码如下: string xml = @"<?xml version=""1.0"" standalone=""no""?>                             <root>                   

  • C#中使用JSON.NET实现JSON、XML相互转换

    官方 JSON.NET 地址 http://james.newtonking.com/pages/json-net.aspx XML TO JSON string xml = @"<?xml version=""1.0"" standalone=""no""?> <root> <person id=""1""> <name>Ala

  • C#实现JSON和对象之间互相转换功能示例

    本文实例讲述了C#实现JSON和对象之间互相转换功能.分享给大家供大家参考,具体如下: 1.首先是声明用户信息对象,DataContract修饰类,表示可以被解析成JSON,DataMember修饰属性,Order表示 解析的顺序,另外Lover是数组列表,表示女朋友个数 Address 表示送货地址,DailyRecord  表示日常记录 using System; using System.Collections.Generic; using System.Linq; using Syste

  • 自定义实现Json字符串向C#对象转变的方法

    这里使用Atrribute的方式实现了Json字符串向C#对象的转变.因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json数组.这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Jso

  • C#中的DataSet、string、DataTable、对象转换成Json的实现代码

    C#中对象,字符串,dataTable.DataReader.DataSet,对象集合转换成Json字符串方法. public class ConvertJson { #region 私有方法 /// <summary> /// 过滤特殊字符 /// </summary> /// <param name="s">字符串</param> /// <returns>json字符串</returns> private s

  • C#实现将json转换为DataTable的方法

    本文实例讲述了C#实现将json转换为DataTable的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: #region 将json转换为DataTable /// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> pr

  • C#实现Json转Unicode的方法

    本文实例讲述了C#实现Json转Unicode的方法.分享给大家供大家参考之用.具体方法如下: 本文实例主要实现输入为带有json格式的文本,输出正常文本的功能. 具体代码如下: private string JsonToUnicode(string input) { input = input.Replace("\\\"", "\""); input = input.Replace("\\/", "/")

  • C#实现集合转换成json格式数据的方法

    本文实例讲述了C#实现集合转换成json格式数据的方法.分享给大家供大家参考,具体如下: /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToJson(DataTable dt) { if (dt != null

  • C#实现json格式转换成对象并更换key的方法

    本文实例讲述了C#实现json格式转换成对象并更换key的方法.分享给大家供大家参考.具体分析如下: 由于是不标准的序列化对象类型,因此你无法通过标准的反序列化类来实现,需要自定义一个序列化类或者简单点,直接自定义一个方法解析Json数据.解析后的数据用Dictionary来存放. string str = "{\"name\": \"甄嬛体\",\"2012-05-04 14:59\": \"5724\"}&quo

随机推荐