using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace DataexchangeServer { /// /// JSON帮助方法 /// public class JSONHelper { /// /// 将json转换为DataTable /// /// 得到的json /// public static DataTable JsonToDataTable(string strJson) { DataTable tb = null; if (strJson.IndexOf("\"|") > -1 || strJson.IndexOf("\"#+#") > -1) { return tb; } strJson = strJson.Replace("\",", "\"|").Replace("\":", "\"#+#").ToString(); //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //获取数据 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split('|'); //创建表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { var dc = new DataColumn(); string[] strCell = str.Split(new string[] { "#+#" }, StringSplitOptions.None); if (strCell[0].Substring(0, 1) == "\"") { int a = strCell[0].Length; dc.ColumnName = strCell[0].Substring(1, a - 2); } else { dc.ColumnName = strCell[0]; } tb.Columns.Add(dc); } tb.AcceptChanges(); } //增加内容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { dr[r] = strRows[r].Split(new string[] { "#+#" }, StringSplitOptions.None)[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } tb.Rows.Add(dr); tb.AcceptChanges(); } return tb; } static object obj = new object(); /// /// 写入文件 /// /// /// public static bool WriteToFile(string msg) { if (msg.Trim() == "") return true; try { lock (obj) { string fileFolder = Environment.CurrentDirectory + @"\log\"; if (!Directory.Exists(fileFolder)) { DirectoryInfo directoryInfo = new DirectoryInfo(fileFolder); directoryInfo.Create(); } string path = fileFolder + DateTime.Now.ToString("yyyyMMdd HH-mm") + ".txt"; using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write)) { byte[] bytes = Encoding.Default.GetBytes(msg); //fs.WriteTimeout = 10000; fs.Write(bytes, 0, bytes.Length); fs.Close(); } return true; } } catch (Exception ex) { return false; } } } }