纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

568 lines
23 KiB

3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.Common;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace ICSSoft.Common
  11. {
  12. public class DataToJsonHelper
  13. {
  14. /* string sql = @"SELECT Identification,y.DepCode,a.ToWarehouseCode AS WarehouseCode
  15. FROM ICSWareHouseLotInfoLog a
  16. INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
  17. INNER JOIN ICSOApplyNegDetail c ON b.TransCode=c.OApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
  18. INNER JOIN ICSOOPick x ON c.SourceDetailID=x.PickID AND c.WorkPoint=x.WorkPoint
  19. INNER JOIN ICSOutsourcingOrder y ON x.OODetailID=y.OODetailID AND x.WorkPoint=y.WorkPoint
  20. GROUP BY Identification,y.DepCode,a.ToWarehouseCode
  21. SELECT Identification,y.OOCode,
  22. a.InvCode,SUM(a.Quantity) AS Quantity,0 AS Amount,c.SourceDetailID
  23. FROM ICSWareHouseLotInfoLog a
  24. INNER JOIN ICSInventoryLotDetail b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint
  25. INNER JOIN ICSOApplyNegDetail c ON b.TransCode=c.OApplyNegCode AND b.TransSequence=c.Sequence AND b.WorkPoint=c.WorkPoint
  26. INNER JOIN ICSOOPick x ON c.SourceDetailID=x.PickID AND c.WorkPoint=x.WorkPoint
  27. INNER JOIN ICSOutsourcingOrder y ON x.OODetailID=y.OODetailID AND x.WorkPoint=y.WorkPoint
  28. GROUP BY Identification,y.OOCode,a.MUSER,a.InvCode,c.SourceDetailID";
  29. DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd, language);
  30. string RelationName = "details";
  31. DataRelation dr = new DataRelation(RelationName, ds.Tables[0].Columns["Identification"], ds.Tables[1].Columns["Identification"]);
  32. ds.Relations.Add(dr);
  33. string aaa = DataToJson.DataSetToJson(ds, RelationName);
  34. */
  35. /// <summary>
  36. /// DataSet转Json字符串,主子结构
  37. /// 需要建立主子表关系,第一张表为主表
  38. /// 会排除关联列
  39. /// </summary>
  40. /// <param name="dataSet"></param>
  41. /// <param name="RelationName">关系名称</param>
  42. /// <returns></returns>
  43. public static string DataSetToJson(DataSet dataSet,string RelationName,string column)
  44. {
  45. //if (!dataSet.Tables[0].Columns.Contains(column))
  46. //{
  47. //}
  48. DataRelation dataRelation = new DataRelation(RelationName, dataSet.Tables[0].Columns[column], dataSet.Tables[1].Columns[column]);
  49. dataSet.Relations.Add(dataRelation);
  50. StringBuilder jsonString = new StringBuilder();
  51. //foreach (DataTable table in dataSet.Tables)
  52. //{
  53. DataTable table = dataSet.Tables[0];
  54. jsonString.Append("[");
  55. DataRowCollection drc = table.Rows;
  56. for (int i = 0; i < drc.Count; i++)
  57. {
  58. DataRow dataRow = drc[i];
  59. jsonString.Append("{");
  60. for (int j = 0; j < table.Columns.Count; j++)
  61. {
  62. string strKey = table.Columns[j].ColumnName;
  63. if (dataSet.Relations[RelationName].ParentColumns.Select(a=>a.Caption).Contains(strKey))
  64. continue;
  65. string strValue = dataRow[j].ToString();
  66. Type type = table.Columns[j].DataType;
  67. jsonString.Append("\"" + strKey + "\":");
  68. strValue = StringFormat(strValue, type);
  69. if (j < table.Columns.Count - 1)
  70. {
  71. jsonString.Append(strValue + ",");
  72. }
  73. else
  74. {
  75. jsonString.Append(strValue);
  76. }
  77. }
  78. jsonString.Append(",\"" + RelationName + "\":");
  79. DataRow[] drs = dataRow.GetChildRows(RelationName);
  80. jsonString.Append("[");
  81. foreach (DataRow dr in drs)
  82. {
  83. DataTable dt = dr.Table;
  84. jsonString.Append("{");
  85. for (int j = 0; j < dt.Columns.Count; j++)
  86. {
  87. string strKey = dt.Columns[j].ColumnName;
  88. if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
  89. continue;
  90. string strValue = dr[j].ToString();
  91. Type type = dt.Columns[j].DataType;
  92. jsonString.Append("\"" + strKey + "\":");
  93. strValue = StringFormat(strValue, type);
  94. if (j < dt.Columns.Count - 1)
  95. {
  96. jsonString.Append(strValue + ",");
  97. }
  98. else
  99. {
  100. jsonString.Append(strValue);
  101. }
  102. }
  103. jsonString.Append("},");
  104. }
  105. if(drs.Length>0)
  106. jsonString.Remove(jsonString.Length - 1, 1);
  107. jsonString.Append("]");
  108. jsonString.Append("},");
  109. }
  110. jsonString.Remove(jsonString.Length - 1, 1);
  111. jsonString.Append("]");
  112. //}
  113. string res = jsonString.ToString();
  114. return res;
  115. }
  116. /// <summary>
  117. /// DataSet转Json字符串,"主-子-子"结构
  118. /// 需要建立主子表关系,第一张表为主表,第二张表为子表,第三张表为子件表
  119. /// 会排除关联列
  120. /// </summary>
  121. /// <param name="dataSet"></param>
  122. /// <param name="RelationName">关系名称</param>
  123. /// <returns></returns>
  124. public static string DataSetToJson(DataSet dataSet,string RelationName,string column,string RelationName2,string column2)
  125. {
  126. //if (!dataSet.Tables[0].Columns.Contains(column))
  127. //{
  128. //}
  129. DataRelation dataRelation = new DataRelation(RelationName, dataSet.Tables[0].Columns[column], dataSet.Tables[1].Columns[column]);
  130. DataRelation dataRelation2 = new DataRelation(RelationName2, dataSet.Tables[1].Columns[column2], dataSet.Tables[2].Columns[column2]);
  131. dataSet.Relations.Add(dataRelation);
  132. dataSet.Relations.Add(dataRelation2);
  133. StringBuilder jsonString = new StringBuilder();
  134. //foreach (DataTable table in dataSet.Tables)
  135. //{
  136. DataTable table = dataSet.Tables[0];
  137. DataTable table2 = dataSet.Tables[1];
  138. jsonString.Append("[");
  139. DataRowCollection drc = table.Rows;
  140. for (int i = 0; i < drc.Count; i++)
  141. {
  142. DataRow dataRow = drc[i];
  143. jsonString.Append("{");
  144. for (int j = 0; j < table.Columns.Count; j++)
  145. {
  146. string strKey = table.Columns[j].ColumnName;
  147. if (dataSet.Relations[RelationName].ParentColumns.Select(a=>a.Caption).Contains(strKey))
  148. continue;
  149. string strValue = dataRow[j].ToString();
  150. Type type = table.Columns[j].DataType;
  151. jsonString.Append("\"" + strKey + "\":");
  152. strValue = StringFormat(strValue, type);
  153. if (j < table.Columns.Count - 1)
  154. {
  155. jsonString.Append(strValue + ",");
  156. }
  157. else
  158. {
  159. jsonString.Append(strValue);
  160. }
  161. }
  162. jsonString.Append(",\"" + RelationName + "\":");
  163. DataRow[] drs = dataRow.GetChildRows(RelationName);
  164. jsonString.Append("[");
  165. foreach (DataRow dr in drs)
  166. {
  167. DataTable dt = dr.Table;
  168. jsonString.Append("{");
  169. for (int j = 0; j < dt.Columns.Count; j++)
  170. {
  171. string strKey = dt.Columns[j].ColumnName;
  172. if (dataSet.Relations[RelationName].ChildColumns.Select(a => a.Caption).Contains(strKey))
  173. continue;
  174. string strValue = dr[j].ToString();
  175. Type type = dt.Columns[j].DataType;
  176. jsonString.Append("\"" + strKey + "\":");
  177. strValue = StringFormat(strValue, type);
  178. if (j < dt.Columns.Count - 1)
  179. {
  180. jsonString.Append(strValue + ",");
  181. }
  182. else
  183. {
  184. jsonString.Append(strValue);
  185. }
  186. }
  187. ////子件表
  188. jsonString.Append(",\"" + RelationName2 + "\":");
  189. //DataRowCollection drc2 = table2.Rows;
  190. //for (int j = 0; j < drc2.Count; j++)
  191. //{
  192. // DataRow dataRow2 = drc2[j];
  193. DataRow[] drss = dr.GetChildRows(RelationName2);//取不到值
  194. jsonString.Append("[");
  195. foreach (DataRow drSec in drss)
  196. {
  197. DataTable dtSec = drSec.Table;
  198. jsonString.Append("{");
  199. for (int k = 0; k < dtSec.Columns.Count; k++)
  200. {
  201. string strKey = dtSec.Columns[k].ColumnName;
  202. if (dataSet.Relations[RelationName2].ChildColumns.Select(a => a.Caption).Contains(strKey))
  203. continue;
  204. string strValue = drSec[k].ToString();
  205. Type type = dtSec.Columns[k].DataType;
  206. jsonString.Append("\"" + strKey + "\":");
  207. strValue = StringFormat(strValue, type);
  208. if (k < dtSec.Columns.Count - 1)
  209. {
  210. jsonString.Append(strValue + ",");
  211. }
  212. else
  213. {
  214. jsonString.Append(strValue);
  215. }
  216. }
  217. jsonString.Append("},");
  218. }
  219. if (drss.Length > 0)
  220. jsonString.Remove(jsonString.Length - 1, 1);
  221. jsonString.Append("]");//detailss的后方括号
  222. jsonString.Append("},");
  223. }
  224. if (drs.Length>0)
  225. jsonString.Remove(jsonString.Length - 1, 1);
  226. jsonString.Append("]");
  227. jsonString.Append("},");
  228. }
  229. jsonString.Remove(jsonString.Length - 1, 1);
  230. jsonString.Append("]");
  231. //}
  232. string res = jsonString.ToString();
  233. return res;
  234. }
  235. #region 私有方法
  236. /// <summary>
  237. /// 过滤特殊字符
  238. /// </summary>
  239. /// <param name="s">字符串</param>
  240. /// <returns>json字符串</returns>
  241. private static string String2Json(String s)
  242. {
  243. StringBuilder sb = new StringBuilder();
  244. for (int i = 0; i < s.Length; i++)
  245. {
  246. char c = s.ToCharArray()[i];
  247. switch (c)
  248. {
  249. case '\"':
  250. sb.Append("\\\""); break;
  251. case '\\':
  252. sb.Append("\\\\"); break;
  253. case '/':
  254. sb.Append("\\/"); break;
  255. case '\b':
  256. sb.Append("\\b"); break;
  257. case '\f':
  258. sb.Append("\\f"); break;
  259. case '\n':
  260. sb.Append("\\n"); break;
  261. case '\r':
  262. sb.Append("\\r"); break;
  263. case '\t':
  264. sb.Append("\\t"); break;
  265. default:
  266. sb.Append(c); break;
  267. }
  268. }
  269. return sb.ToString();
  270. }
  271. /// <summary>
  272. /// 格式化字符型、日期型、布尔型
  273. /// </summary>
  274. /// <param name="str"></param>
  275. /// <param name="type"></param>
  276. /// <returns></returns>
  277. private static string StringFormat(string str, Type type)
  278. {
  279. if (type == typeof(string))
  280. {
  281. str = String2Json(str);
  282. str = "\"" + str + "\"";
  283. }
  284. else if (type == typeof(DateTime))
  285. {
  286. str = "\"" + str + "\"";
  287. }
  288. else if (type == typeof(bool))
  289. {
  290. str = str.ToLower();
  291. }
  292. else if (type != typeof(string) && string.IsNullOrEmpty(str))
  293. {
  294. str = "\"" + str + "\"";
  295. }
  296. return str;
  297. }
  298. #endregion
  299. #region list转换成JSON
  300. /// <summary>
  301. /// list转换为Json
  302. /// </summary>
  303. /// <typeparam name="T"></typeparam>
  304. /// <param name="list"></param>
  305. /// <returns></returns>
  306. public static string ListToJson<T>(IList<T> list)
  307. {
  308. object obj = list[0];
  309. return ListToJson<T>(list, obj.GetType().Name);
  310. }
  311. /// <summary>
  312. /// list转换为json
  313. /// </summary>
  314. /// <typeparam name="T1"></typeparam>
  315. /// <param name="list"></param>
  316. /// <param name="p"></param>
  317. /// <returns></returns>
  318. private static string ListToJson<T>(IList<T> list, string JsonName)
  319. {
  320. StringBuilder Json = new StringBuilder();
  321. if (string.IsNullOrEmpty(JsonName))
  322. JsonName = list[0].GetType().Name;
  323. Json.Append("{\"" + JsonName + "\":[");
  324. if (list.Count > 0)
  325. {
  326. for (int i = 0; i < list.Count; i++)
  327. {
  328. T obj = Activator.CreateInstance<T>();
  329. PropertyInfo[] pi = obj.GetType().GetProperties();
  330. Json.Append("{");
  331. for (int j = 0; j < pi.Length; j++)
  332. {
  333. Type type = pi[j].GetValue(list[i], null).GetType();
  334. Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
  335. if (j < pi.Length - 1)
  336. {
  337. Json.Append(",");
  338. }
  339. }
  340. Json.Append("}");
  341. if (i < list.Count - 1)
  342. {
  343. Json.Append(",");
  344. }
  345. }
  346. }
  347. Json.Append("]}");
  348. return Json.ToString();
  349. }
  350. #endregion
  351. #region 对象转换为Json
  352. /// <summary>
  353. /// 对象转换为json
  354. /// </summary>
  355. /// <param name="jsonObject">json对象</param>
  356. /// <returns>json字符串</returns>
  357. public static string ToJson(object jsonObject)
  358. {
  359. string jsonString = "{";
  360. PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
  361. for (int i = 0; i < propertyInfo.Length; i++)
  362. {
  363. object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
  364. string value = string.Empty;
  365. if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
  366. {
  367. value = "'" + objectValue.ToString() + "'";
  368. }
  369. else if (objectValue is string)
  370. {
  371. value = "'" + ToJson(objectValue.ToString()) + "'";
  372. }
  373. else if (objectValue is IEnumerable)
  374. {
  375. value = ToJson((IEnumerable)objectValue);
  376. }
  377. else
  378. {
  379. value = ToJson(objectValue.ToString());
  380. }
  381. jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
  382. }
  383. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  384. return jsonString + "}";
  385. }
  386. #endregion
  387. #region 对象集合转换为json
  388. /// <summary>
  389. /// 对象集合转换为json
  390. /// </summary>
  391. /// <param name="array">对象集合</param>
  392. /// <returns>json字符串</returns>
  393. public static string ToJson(IEnumerable array)
  394. {
  395. string jsonString = "{";
  396. foreach (object item in array)
  397. {
  398. jsonString += ToJson(item) + ",";
  399. }
  400. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  401. return jsonString + "]";
  402. }
  403. #endregion
  404. #region 普通集合转换Json
  405. /// <summary>
  406. /// 普通集合转换Json
  407. /// </summary>
  408. /// <param name="array">集合对象</param>
  409. /// <returns>Json字符串</returns>
  410. public static string ToArrayString(IEnumerable array)
  411. {
  412. string jsonString = "[";
  413. foreach (object item in array)
  414. {
  415. jsonString = ToJson(item.ToString()) + ",";
  416. }
  417. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  418. return jsonString + "]";
  419. }
  420. #endregion
  421. #region DataSet转换为Json
  422. /// <summary>
  423. /// DataSet转换为Json
  424. /// </summary>
  425. /// <param name="dataSet">DataSet对象</param>
  426. /// <returns>Json字符串</returns>
  427. public static string ToJson(DataSet dataSet)
  428. {
  429. string jsonString = "{";
  430. foreach (DataTable table in dataSet.Tables)
  431. {
  432. jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
  433. }
  434. jsonString = jsonString.TrimEnd(',');
  435. return jsonString + "}";
  436. }
  437. #endregion
  438. #region Datatable转换为Json
  439. /// <summary>
  440. /// Datatable转换为Json
  441. /// </summary>
  442. /// <param name="table">Datatable对象</param>
  443. /// <returns>Json字符串</returns>
  444. public static string ToJson(DataTable dt)
  445. {
  446. StringBuilder jsonString = new StringBuilder();
  447. jsonString.Append("[");
  448. DataRowCollection drc = dt.Rows;
  449. for (int i = 0; i < drc.Count; i++)
  450. {
  451. jsonString.Append("{");
  452. for (int j = 0; j < dt.Columns.Count; j++)
  453. {
  454. string strKey = dt.Columns[j].ColumnName;
  455. string strValue = drc[i][j].ToString();
  456. Type type = dt.Columns[j].DataType;
  457. jsonString.Append("\"" + strKey + "\":");
  458. strValue = StringFormat(strValue, type);
  459. if (j < dt.Columns.Count - 1)
  460. {
  461. jsonString.Append(strValue + ",");
  462. }
  463. else
  464. {
  465. jsonString.Append(strValue);
  466. }
  467. }
  468. jsonString.Append("},");
  469. }
  470. jsonString.Remove(jsonString.Length - 1, 1);
  471. jsonString.Append("]");
  472. return jsonString.ToString();
  473. }
  474. /// <summary>
  475. /// DataTable转换为Json
  476. /// </summary>
  477. public static string ToJson(DataTable dt, string jsonName)
  478. {
  479. StringBuilder Json = new StringBuilder();
  480. if (string.IsNullOrEmpty(jsonName))
  481. jsonName = dt.TableName;
  482. Json.Append("{\"" + jsonName + "\":[");
  483. if (dt.Rows.Count > 0)
  484. {
  485. for (int i = 0; i < dt.Rows.Count; i++)
  486. {
  487. Json.Append("{");
  488. for (int j = 0; j < dt.Columns.Count; j++)
  489. {
  490. Type type = dt.Rows[i][j].GetType();
  491. Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
  492. if (j < dt.Columns.Count - 1)
  493. {
  494. Json.Append(",");
  495. }
  496. }
  497. Json.Append("}");
  498. if (i < dt.Rows.Count - 1)
  499. {
  500. Json.Append(",");
  501. }
  502. }
  503. }
  504. Json.Append("]}");
  505. return Json.ToString();
  506. }
  507. #endregion
  508. #region DataReader转换为Json
  509. /// <summary>
  510. /// DataReader转换为Json
  511. /// </summary>
  512. /// <param name="dataReader">DataReader对象</param>
  513. /// <returns>Json字符串</returns>
  514. public static string ToJson(DbDataReader dataReader)
  515. {
  516. StringBuilder jsonString = new StringBuilder();
  517. jsonString.Append("[");
  518. while (dataReader.Read())
  519. {
  520. jsonString.Append("{");
  521. for (int i = 0; i < dataReader.FieldCount; i++)
  522. {
  523. Type type = dataReader.GetFieldType(i);
  524. string strKey = dataReader.GetName(i);
  525. string strValue = dataReader[i].ToString();
  526. jsonString.Append("\"" + strKey + "\":");
  527. strValue = StringFormat(strValue, type);
  528. if (i < dataReader.FieldCount - 1)
  529. {
  530. jsonString.Append(strValue + ",");
  531. }
  532. else
  533. {
  534. jsonString.Append(strValue);
  535. }
  536. }
  537. jsonString.Append("},");
  538. }
  539. dataReader.Close();
  540. jsonString.Remove(jsonString.Length - 1, 1);
  541. jsonString.Append("]");
  542. return jsonString.ToString();
  543. }
  544. #endregion
  545. }
  546. }