DataTable、Dataset转Json
DataTable、Dataset转Json
一、DataTable转Json
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static string DataTableToJson1(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(); }
二、Dataset转Json
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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(); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static string DataTableToJson2(DataTable dt) { StringBuilder Json = new StringBuilder(); Json.Append("{\"" + dt.TableName + "\":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("\r\n" + "{\"device\":" + "\r\n" + "{"); for (int j = 0; j < dt.Columns.Count; j++) { string columName = dt.Columns[j].ColumnName.ToString(); string columValue = dt.Rows[i][j].ToString(); if (j == 9)//"radios":{"wifiMAC":~~}, Json.Append("\"radios\":{\"" + columName + "\":\"" + columValue + "\"}"); else if (j == 10 || j == 11)//"partDetails":{"mainLogicBoardSerialNumber":~~, "batterySerialNumber":~~ } { if (j == 10) Json.Append("\"partDetails\":{\"" + columName + "\":\"" + columValue + "\""); else Json.Append("\"" + columName + "\":\"" + columValue + "\"}}"); } else if (j == 12) Json.Append("\"order\":{\"" + columName + "\":\"" + columValue + "\""); else if (j == 16) Json.Append("\"" + columName + "\":\"" + columValue + "\"}"); else Json.Append("\"" + columName + "\":\"" + columValue + "\""); if (j < dt.Columns.Count - 1 ) Json.Append(","); } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("\r\n" + "]}"); return Json.ToString(); }
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15079494.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
![](https://images.cnblogs.com/cnblogs_com/wml-it/2196906/o_230823011905_wxgzhss.png)