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代码检验、检验、美化、格式化工具:
json在线格式化工具:
在线xml/json互相转换工具:
json代码在线格式化/美化/压缩/编辑/转换工具:
在线json压缩/转义工具:
c语言风格/html/css/json代码格式化美化工具: