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 = ; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = ; 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 - )
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - , );
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 = ; 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 > )
{
JsonString.Append("{ ");
JsonString.Append("\"T_blog\":[ ");
for (int i = ; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = ; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
}
else if (j == dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
}
}
/**//**/
/**//*end Of String*/
if (i == dt.Rows.Count - )
{
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 == )
return "";
StringBuilder sb = new StringBuilder("[");
foreach (DataRow row in source.Rows)
{
sb.Append("[");
for (int i = ; i < source.Columns.Count; i++)
{
sb.Append('"' + row[i].ToString() + "\",");
}
sb.Remove(sb.Length - , );
sb.Append("],");
}
sb.Remove(sb.Length - , );
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 > )
{
JsonString.Append("{ ");
JsonString.Append("\"TableInfo\":[ ");
for (int i = ; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = ; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
}
else if (j == dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
}
}
/**/
/*end Of String*/
if (i == dt.Rows.Count - )
{
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 = ; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = ; 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 - , );
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - , );
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 > )
{
for (int i = ; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = ; j < dt.Columns.Count; j++)
{
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
if (j < dt.Columns.Count - )
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - )
{
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 > )
{
json =ToJson(ds.Tables[]);
}
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 > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}
if (dataTable.Columns.Count == )
{
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
http://www.jb51.net/article/49116.htm
C#中把Datatable转换为Json的5个代码实例的更多相关文章
- Datatable转换为Json 然后,Json数据导入 js 档
C#在里面Datatable转换为Json的5代码示例 /// <summary> /// Datatable转换为Json /// </summary> /// <pa ...
- 将XML文件中的内容转换为Json对象
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;u ...
- Datatable转换为Json
/// <summary> /// Datatable转换为Json /// </summary> /// <param name="table"&g ...
- Datatable转换为Json 的方法
/// <summary> /// Datatable转换为Json /// </summary> /// <param n ...
- .NET DataTable转换为JSON格式的字符串
在进行数据传递的时候,有时我们需要通过Ajax的方式或者其他的方式传递一个数据列表,可以将DataTable或者其他形式的数据列表转换为JSON的格式,通过Ajax实体的形式进行传递. 比如说: // ...
- DataTable转换为Json字符串的三种方法
//第一种:使用StringBuilder public string DataTableToJson(DataTable table) { var JsonString = new StringB ...
- DataTable转换为Json格式
private string DataTableToJson(DataTable dt) { string Json = ""; Json = Json + "[&quo ...
- DataTable转换为JSON数组
最后的格式为:[{},{},...] StringBuilder DataTableToJSON(DataTable dt) { string columnName; StringBuilder bu ...
- 将List<Map>中的datas转换为json格式写入文件
private static boolean writeToTextFileByJson(List<Map<String, Object>> datas, String tit ...
随机推荐
- 必备:常用px,pt,em换算表(转)
常用px,pt,em换算表 pt (point,磅):是一个物理长度单位,指的是72分之一英寸. px (pixel,像素):是一个虚拟长度单位,是计算机系统的数字化图像长度单位,如果px要换算成物理 ...
- JavaWeb动态导出Excel可弹出下载
由于项目需求,需要将数据导出成Excel表格,并且可选择导出项,可下载.项目使用的Spring+Mybatis+SpringMVC框架,利用Apache POI导出Excel.POI具体使用请自行百度 ...
- 清除BOM头源码
BOM: Byte Order Mark UTF-8 BOM又叫UTF-8 签名,其实UTF-8 的BOM对UFT-8没有作用,是为了支援UTF-16,UTF-32才加上的BOM,BOM签名的意思就是 ...
- 给自定义cell赋值代码
// // ViewController.m // 11 - 投资管理 - 李洪强 // // Created by vic fan on 16/4/8. // Copyright © 201 ...
- zk label控件内容换行
Label控件本身无法换行,不过div却可以,只要设置了div的宽度,那么就想如果在Label控件外套个div会怎样,结果可喜可乐: <div width="80px"> ...
- B-树的插入、查找、删除
转自:http://blog.163.com/zhoumhan_0351/blog/static/39954227200910231032917/ 前面讨论的查找都是内查询算法,被查询的数据都在内存. ...
- c语言中的文件流
一.打开和关闭文件 #include int main( void ) { FILE* pReadFile = fopen( "E:\\mytest.txt", "r&q ...
- python操作Excel读写--使用xlrd和xlwt
一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境. 进入到解压文件路径,输入 setup.py ...
- Python起步(2)
单行注释:#多行注释:'''或""" 一条语句写在一行之内,不需要分号分隔两条语句在同一行,中间分号隔开缩进语句块中只有一条语句,可以直接写在“:”之后使用“\”进行续行 ...
- Windows NT驱动程序的基本结构和实例
Windows驱动程序分为两类:一类是不支持即插即用功能的NT式驱动程序:另一类是支持即插即用功能的WDM驱动程序. NT式驱动的基本结构: 1)驱动加载过程与驱动入口函数DriverEntry: 驱 ...