ConvertToJson.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Data;
  5. using System.Reflection;
  6. using System.Collections;
  7. using System.Data.Common;
  8. using System.Web.Script.Serialization;
  9. using System.IO;
  10. namespace Bowin.Common.JSON
  11. {
  12. public static class ConvertToJson
  13. {
  14. #region 私有方法
  15. /// <summary>
  16. /// 过滤特殊字符
  17. /// </summary>
  18. private static string String2Json(String s)
  19. {
  20. StringBuilder sb = new StringBuilder();
  21. for (int i = 0; i < s.Length; i++)
  22. {
  23. char c = s.ToCharArray()[i];
  24. switch (c)
  25. {
  26. case '\"':
  27. sb.Append("\\\""); break;
  28. case '\\':
  29. sb.Append("\\\\"); break;
  30. case '/':
  31. sb.Append("\\/"); break;
  32. case '\b':
  33. sb.Append("\\b"); break;
  34. case '\f':
  35. sb.Append("\\f"); break;
  36. case '\n':
  37. sb.Append("\\n"); break;
  38. case '\r':
  39. sb.Append("\\r"); break;
  40. case '\t':
  41. sb.Append("\\t"); break;
  42. default:
  43. sb.Append(c); break;
  44. }
  45. }
  46. return sb.ToString();
  47. }
  48. public static string JsStrFormat(string Str)
  49. {
  50. Str = Str.Replace("\"", """);
  51. Str = Str.Replace("'", "'");
  52. Str = Str.Replace("[", "[");
  53. Str = Str.Replace("]", "]");
  54. Str = Str.Replace("{", "{");
  55. Str = Str.Replace("}", "}");
  56. Str = Str.Replace("+", "+");
  57. Str = Str.Replace("*", "*");
  58. //Str = Str.Replace("\","\");
  59. //Str = Str.Replace("|", "|");
  60. Str = Str.Replace("^", "^");
  61. Str = Str.Replace("$", "$");
  62. //Str = Str.Replace("?", "?");
  63. Str = Str.Replace("\r", " ");
  64. Str = Str.Replace("\n", " ");
  65. Str = Str.Replace("\t", " ");
  66. Str = Str.Replace("\b", " ");
  67. Str = Str.Replace("\f", " ");
  68. return Str;
  69. }
  70. /// <summary>
  71. /// 格式化字符型、日期型、布尔型
  72. /// </summary>
  73. private static string StringFormat(string str, Type type)
  74. {
  75. if (type == typeof(string))
  76. {
  77. str = String2Json(str);
  78. str = "\"" + str + "\"";
  79. }
  80. else if (type == typeof(DateTime))
  81. {
  82. str = "\"" + str + "\"";
  83. }
  84. else if (type == typeof(bool))
  85. {
  86. str = str.ToLower();
  87. }
  88. else if (type != typeof(string) && string.IsNullOrEmpty(str))
  89. {
  90. str = "\"" + str + "\"";
  91. }
  92. return str;
  93. }
  94. #endregion
  95. #region List转换成Json
  96. /// <summary>
  97. /// List转换成Json
  98. /// </summary>
  99. public static string ListToJson<T>(IList<T> list)
  100. {
  101. object obj = list[0];
  102. return ListToJson<T>(list, obj.GetType().Name);
  103. }
  104. /// <summary>
  105. /// List转换成Json
  106. /// </summary>
  107. public static string ListToJson<T>(IList<T> list, string jsonName)
  108. {
  109. StringBuilder Json = new StringBuilder();
  110. if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
  111. Json.Append("{\"" + jsonName + "\":[");
  112. if (list.Count > 0)
  113. {
  114. for (int i = 0; i < list.Count; i++)
  115. {
  116. T obj = Activator.CreateInstance<T>();
  117. PropertyInfo[] pi = obj.GetType().GetProperties();
  118. Json.Append("{");
  119. for (int j = 0; j < pi.Length; j++)
  120. {
  121. Type type = pi[j].GetValue(list[i], null).GetType();
  122. Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
  123. if (j < pi.Length - 1)
  124. {
  125. Json.Append(",");
  126. }
  127. }
  128. Json.Append("}");
  129. if (i < list.Count - 1)
  130. {
  131. Json.Append(",");
  132. }
  133. }
  134. }
  135. Json.Append("]}");
  136. return Json.ToString();
  137. }
  138. #endregion
  139. #region 对象转换为Json
  140. /// <summary>
  141. /// 对象转换为Json
  142. /// </summary>
  143. /// <param name="jsonObject">对象</param>
  144. /// <returns>Json字符串</returns>
  145. public static string ToJson(object jsonObject)
  146. {
  147. //序列化对象为json数据
  148. JavaScriptSerializer j = new JavaScriptSerializer();
  149. return j.Serialize(jsonObject);
  150. }
  151. public static string ToJson<T>(this T jsonObject)
  152. {
  153. return ToJson((object)jsonObject);
  154. }
  155. #endregion
  156. #region 对象集合转换Json
  157. /// <summary>
  158. /// 对象集合转换Json
  159. /// </summary>
  160. /// <param name="array">集合对象</param>
  161. /// <returns>Json字符串</returns>
  162. public static string ToJson(IEnumerable array)
  163. {
  164. string jsonString = "[";
  165. foreach (object item in array)
  166. {
  167. jsonString += ToJson(item) + ",";
  168. }
  169. jsonString = jsonString.Trim(',');
  170. return jsonString + "]";
  171. }
  172. #endregion
  173. #region 普通集合转换Json
  174. /// <summary>
  175. /// 普通集合转换Json
  176. /// </summary>
  177. /// <param name="array">集合对象</param>
  178. /// <returns>Json字符串</returns>
  179. public static string ToArrayString(IEnumerable array)
  180. {
  181. string jsonString = "[";
  182. foreach (object item in array)
  183. {
  184. jsonString = ToJson(item.ToString()) + ",";
  185. }
  186. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  187. return jsonString + "]";
  188. }
  189. #endregion
  190. #region DataSet转换为Json
  191. /// <summary>
  192. /// DataSet转换为Json
  193. /// </summary>
  194. /// <param name="dataSet">DataSet对象</param>
  195. /// <returns>Json字符串</returns>
  196. public static string ToJson(DataSet dataSet)
  197. {
  198. string jsonString = "{";
  199. foreach (DataTable table in dataSet.Tables)
  200. {
  201. jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
  202. }
  203. jsonString = jsonString.TrimEnd(',');
  204. return jsonString + "}";
  205. }
  206. #endregion
  207. #region Datatable转换为Json
  208. /// <summary>
  209. /// Datatable转换为Json
  210. /// </summary>
  211. /// <param name="table">Datatable对象</param>
  212. /// <returns>Json字符串</returns>
  213. public static string ToJson(DataTable dt)
  214. {
  215. StringBuilder jsonString = new StringBuilder();
  216. jsonString.Append("[");
  217. DataRowCollection drc = dt.Rows;
  218. for (int i = 0; i < drc.Count; i++)
  219. {
  220. jsonString.Append("{");
  221. for (int j = 0; j < dt.Columns.Count; j++)
  222. {
  223. string strKey = dt.Columns[j].ColumnName;
  224. string strValue = drc[i][j].ToString();
  225. Type type = dt.Columns[j].DataType;
  226. jsonString.Append("\"" + strKey + "\":");
  227. strValue = StringFormat(strValue, type);
  228. if (j < dt.Columns.Count - 1)
  229. {
  230. jsonString.Append(strValue + ",");
  231. }
  232. else
  233. {
  234. jsonString.Append(strValue);
  235. }
  236. }
  237. jsonString.Append("},");
  238. }
  239. jsonString.Remove(jsonString.Length - 1, 1);
  240. jsonString.Append("]");
  241. return jsonString.ToString();
  242. }
  243. /// <summary>
  244. /// DataTable转换为Json
  245. /// </summary>
  246. public static string ToJson(DataTable dt, string jsonName)
  247. {
  248. StringBuilder Json = new StringBuilder();
  249. if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
  250. Json.Append("{\"" + jsonName + "\":[");
  251. if (dt.Rows.Count > 0)
  252. {
  253. for (int i = 0; i < dt.Rows.Count; i++)
  254. {
  255. Json.Append("{");
  256. for (int j = 0; j < dt.Columns.Count; j++)
  257. {
  258. Type type = dt.Rows[i][j].GetType();
  259. Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
  260. if (j < dt.Columns.Count - 1)
  261. {
  262. Json.Append(",");
  263. }
  264. }
  265. Json.Append("}");
  266. if (i < dt.Rows.Count - 1)
  267. {
  268. Json.Append(",");
  269. }
  270. }
  271. }
  272. Json.Append("]}");
  273. return Json.ToString();
  274. }
  275. #endregion
  276. #region DataReader转换为Json
  277. /// <summary>
  278. /// DataReader转换为Json
  279. /// </summary>
  280. /// <param name="dataReader">DataReader对象</param>
  281. /// <returns>Json字符串</returns>
  282. public static string ToJson(DbDataReader dataReader)
  283. {
  284. StringBuilder jsonString = new StringBuilder();
  285. jsonString.Append("[");
  286. while (dataReader.Read())
  287. {
  288. jsonString.Append("{");
  289. for (int i = 0; i < dataReader.FieldCount; i++)
  290. {
  291. Type type = dataReader.GetFieldType(i);
  292. string strKey = dataReader.GetName(i);
  293. string strValue = dataReader[i].ToString();
  294. jsonString.Append("\"" + strKey + "\":");
  295. strValue = StringFormat(strValue, type);
  296. if (i < dataReader.FieldCount - 1)
  297. {
  298. jsonString.Append(strValue + ",");
  299. }
  300. else
  301. {
  302. jsonString.Append(strValue);
  303. }
  304. }
  305. jsonString.Append("},");
  306. }
  307. dataReader.Close();
  308. jsonString.Remove(jsonString.Length - 1, 1);
  309. jsonString.Append("]");
  310. return jsonString.ToString();
  311. }
  312. #endregion
  313. #region Datatable转换为(不完美)Json ,格式为[ ['A',1],['B',2] ]
  314. /// <summary>
  315. /// Datatable转换为(不完美)Json ,格式为[ ['A',1],['B',2] ]
  316. /// </summary>
  317. /// <param name="table">Datatable对象</param>
  318. /// <returns>Json字符串</returns>
  319. public static string ToJson2(DataTable dt)
  320. {
  321. string json = string.Empty;
  322. for (int i = 0; i < dt.Rows.Count; i++)
  323. {
  324. if (i == 0)
  325. {
  326. json += "[";
  327. }
  328. json += "['" + dt.Rows[i][0].ToString() + "'," + dt.Rows[i][1].ToString() + "],";
  329. if (i == dt.Rows.Count - 1)
  330. {
  331. json = json.Trim(',') + "]";
  332. }
  333. }
  334. return json;
  335. }
  336. #endregion
  337. #region DataTable转换为JS ExtTree
  338. /// <summary>
  339. /// Table转换为JS ExtTree
  340. /// </summary>
  341. /// <param name="dt"></param>
  342. /// <param name="pid"></param>
  343. /// <returns></returns>
  344. public static string TableToExtTree(DataTable dt, string pid)
  345. {
  346. string rtn = "";
  347. try
  348. {
  349. foreach (DataRow dr in dt.Select("pid=" + pid))
  350. {
  351. if (rtn.Length > 0) rtn += ",";
  352. string check = "null";
  353. string other = "";
  354. if (dt.Columns.Contains("Other")) other = dr["Other"].ToString();
  355. if (dt.Columns.Contains("checked")) check = dr["checked"].ToString().Trim() == "0" ? "false" : "true";
  356. rtn += "{" + string.Format("id:\"{0}\",pid:\"{1}\",Name:\"{2}\",Url:\"{3}\",ImgUrl:\"{4}\",checked:{6},Child:{5},Other:'{7}'",
  357. dr["id"].ToString(),
  358. dr["pid"].ToString(),
  359. JsStrFormat(dr["Name"].ToString()),
  360. JsStrFormat(dr["Url"].ToString()),
  361. JsStrFormat(dr["ImgUrl"].ToString()),
  362. TableToExtTree(dt, dr["id"].ToString()),
  363. check,
  364. JsStrFormat(other)
  365. ) + "}";
  366. }
  367. }
  368. catch { }
  369. rtn = "[" + rtn + "]";
  370. return rtn;
  371. }
  372. #endregion
  373. }
  374. }