标签:
1 /// <summary> 2 /// 将DataTable转为Json字符串 3 /// </summary> 4 /// <param name="dt"></param> 5 /// <returns></returns> 6 public static string DataTable2Json(DataTable dt) 7 { 8 9 if (dt.Rows.Count == 0) 10 { 11 return ""; 12 } 13 14 StringBuilder jsonBuilder = new StringBuilder(); 15 // jsonBuilder.Append("{"); 16 //jsonBuilder.Append(dt.TableName.ToString()); 17 jsonBuilder.Append("[");//转换成多个model的形式 18 for (int i = 0; i < dt.Rows.Count; i++) 19 { 20 jsonBuilder.Append("{"); 21 for (int j = 0; j < dt.Columns.Count; j++) 22 { 23 //保留两位 24 if (dt.Columns[j].DataType.ToString() == "System.Decimal") 25 { 26 27 jsonBuilder.Append("\""); 28 jsonBuilder.Append(dt.Columns[j].ColumnName); 29 jsonBuilder.Append("\":\""); 30 try 31 { 32 jsonBuilder.Append(Convert.ToDecimal(dt.Rows[i][j]).ToString("f2")); 33 34 } 35 catch (Exception) 36 { 37 38 jsonBuilder.Append(0); 39 } 40 jsonBuilder.Append("\","); 41 } 42 //时间类型则变形 43 else if (dt.Columns[j].DataType.ToString() == "System.DateTime") 44 { 45 jsonBuilder.Append("\""); 46 jsonBuilder.Append(dt.Columns[j].ColumnName); 47 jsonBuilder.Append("\":\""); 48 try 49 { 50 jsonBuilder.Append(Convert.ToDateTime(dt.Rows[i][j]).ToString("yyyy/MM/dd HH:mm:ss")); 51 } 52 catch (Exception) 53 { 54 jsonBuilder.Append(""); 55 } 56 jsonBuilder.Append("\","); 57 } 58 else 59 { 60 jsonBuilder.Append("\""); 61 jsonBuilder.Append(dt.Columns[j].ColumnName); 62 jsonBuilder.Append("\":\""); 63 64 try 65 { 66 jsonBuilder.Append(dt.Rows[i][j].ToString()); 67 68 } 69 catch (Exception) 70 { 71 72 jsonBuilder.Append(""); 73 } 74 jsonBuilder.Append("\","); 75 } 76 77 } 78 jsonBuilder.Remove(jsonBuilder.Length - 1, 1); 79 jsonBuilder.Append("},"); 80 } 81 jsonBuilder.Remove(jsonBuilder.Length - 1, 1); 82 jsonBuilder.Append("]"); 83 // jsonBuilder.Append("}"); 84 85 return Regex.Replace(jsonBuilder.ToString(), @"[\r\n]", ""); 86 }
标签:
原文地址:http://www.cnblogs.com/twzy/p/5120696.html