先上来代码:
public static string DataTableToJSON(DataTable dt, string dtName) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jw = new JsonTextWriter(sw)) { JsonSerializer ser = new JsonSerializer(); jw.WriteStartObject(); jw.WritePropertyName(dtName); jw.WriteStartArray(); foreach (DataRow dr in dt.Rows) { jw.WriteStartObject(); foreach (DataColumn dc in dt.Columns) { jw.WritePropertyName(dc.ColumnName); ser.Serialize(jw, dr[dc].ToString()); } jw.WriteEndObject(); } jw.WriteEndArray(); jw.WriteEndObject(); sw.Close(); jw.Close(); } return sb.ToString(); }
例如上传一个dt 得到一个字符串
string jsonData = JsonHelper.DataTableToJSON(dt, "Products");
{"Products":[{"orderid":"11077","customerid":"RATTC","shipname":"Rattlesnake Canyon Grocery","shipcity":"Albuquerque","RowNumber":"1"},{"orderid":"11076","customerid":"BONAP","shipname":"Bon app'","shipcity":"Marseille","RowNumber":"2"},{"orderid":"11075","customerid":"RICSU","shipname":"Richter Supermarkt","shipcity":"Genève","RowNumber":"3"},{"orderid":"11074","customerid":"SIMOB","shipname":"Simons bistro","shipcity":"Kobenhavn","RowNumber":"4"},{"orderid":"11073","customerid":"PERIC","shipname":"Pericles Comidas clásicas","shipcity":"México D.F.","RowNumber":"5"},{"orderid":"11072","customerid":"ERNSH","shipname":"Ernst Handel","shipcity":"Graz","RowNumber":"6"},{"orderid":"11071","customerid":"LILAS","shipname":"LILA-Supermercado","shipcity":"Barquisimeto","RowNumber":"7"},{"orderid":"11070","customerid":"LEHMS","shipname":"Lehmanns Marktstand","shipcity":"Frankfurt a.M.","RowNumber":"8"},{"orderid":"11069","customerid":"TORTU","shipname":"Tortuga Restaurante","shipcity":"México D.F.","RowNumber":"9"},{"orderid":"11068","customerid":"QUEEN","shipname":"Queen Cozinha","shipcity":"Sao Paulo","RowNumber":"10"},{"orderid":"11067","customerid":"DRACD","shipname":"Drachenblut Delikatessen","shipcity":"Aachen","RowNumber":"11"},{"orderid":"11066","customerid":"WHITC","shipname":"White Clover Markets","shipcity":"Seattle","RowNumber":"12"},{"orderid":"11065","customerid":"LILAS","shipname":"LILA-Supermercado","shipcity":"Barquisimeto","RowNumber":"13"},{"orderid":"11064","customerid":"SAVEA","shipname":"Save-a-lot Markets","shipcity":"Boise","RowNumber":"14"},{"orderid":"11063","customerid":"HUNGO","shipname":"Hungry Owl All-Night Grocers","shipcity":"Cork","RowNumber":"15"},{"orderid":"11062","customerid":"REGGC","shipname":"Reggiani Caseifici","shipcity":"Reggio Emilia","RowNumber":"16"},{"orderid":"11061","customerid":"GREAL","shipname":"Great Lakes Food Market","shipcity":"Eugene","RowNumber":"17"},{"orderid":"11060","customerid":"FRANS","shipname":"Franchi S.p.A.","shipcity":"Torino","RowNumber":"18"},{"orderid":"11059","customerid":"RICAR","shipname":"Ricardo Adocicados","shipcity":"Rio de Janeiro","RowNumber":"19"},{"orderid":"11058","customerid":"BLAUS","shipname":"Blauer See Delikatessen","shipcity":"Mannheim","RowNumber":"20"}]}
很明显得到了一个json集合