今天总结一下关于DataTable,XML转JSON的方法:
首先需要引入命名空间: using Newtonsoft.Json 1 public string DataTableToJsonWithStringBuilder(DataTable table)
2 { 3 var jsonString = new StringBuilder(); 4 if (table.Rows.Count > 0) 5 { 6 jsonString.Append("["); 7 for (int i = 0; i < table.Rows.Count; i++) 8 { 9 jsonString.Append("{"); 10 for (int j = 0; j < table.Columns.Count; j++) 11 { 12 if (j < table.Columns.Count - 1) 13 { 14 jsonString.Append(""" + table.Columns[j].ColumnName.ToString() 15 + "":" + """ 16 + table.Rows[i][j].ToString() + "","); 17 } 18 else if (j == table.Columns.Count - 1) 19 { 20 jsonString.Append(""" + table.Columns[j].ColumnName.ToString() 21 + "":" + """ 22 + table.Rows[i][j].ToString() + """); 23 } 24 } 25 if (i == table.Rows.Count - 1) 26 { 27 jsonString.Append("}"); 28 } 29 else 30 { 31 jsonString.Append("},"); 32 } 33 } 34 jsonString.Append("]"); 35 } 36 return jsonString.ToString(); 37 }
调用:
var xmlToJson = DataTableToJsonWithStringBuilder(newdt);// datatable转json数组
//XML转JSON
var xmlToJson1 = JsonConvert.SerializeXmlNode(child, Newtonsoft.Json.Formatting.None, true);