纽威
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.

442 lines
17 KiB

3 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. #region 私有方法
  117. /// <summary>
  118. /// 过滤特殊字符
  119. /// </summary>
  120. /// <param name="s">字符串</param>
  121. /// <returns>json字符串</returns>
  122. private static string String2Json(String s)
  123. {
  124. StringBuilder sb = new StringBuilder();
  125. for (int i = 0; i < s.Length; i++)
  126. {
  127. char c = s.ToCharArray()[i];
  128. switch (c)
  129. {
  130. case '\"':
  131. sb.Append("\\\""); break;
  132. case '\\':
  133. sb.Append("\\\\"); break;
  134. case '/':
  135. sb.Append("\\/"); break;
  136. case '\b':
  137. sb.Append("\\b"); break;
  138. case '\f':
  139. sb.Append("\\f"); break;
  140. case '\n':
  141. sb.Append("\\n"); break;
  142. case '\r':
  143. sb.Append("\\r"); break;
  144. case '\t':
  145. sb.Append("\\t"); break;
  146. default:
  147. sb.Append(c); break;
  148. }
  149. }
  150. return sb.ToString();
  151. }
  152. /// <summary>
  153. /// 格式化字符型、日期型、布尔型
  154. /// </summary>
  155. /// <param name="str"></param>
  156. /// <param name="type"></param>
  157. /// <returns></returns>
  158. private static string StringFormat(string str, Type type)
  159. {
  160. if (type == typeof(string))
  161. {
  162. str = String2Json(str);
  163. str = "\"" + str + "\"";
  164. }
  165. else if (type == typeof(DateTime))
  166. {
  167. str = "\"" + str + "\"";
  168. }
  169. else if (type == typeof(bool))
  170. {
  171. str = str.ToLower();
  172. }
  173. else if (type != typeof(string) && string.IsNullOrEmpty(str))
  174. {
  175. str = "\"" + str + "\"";
  176. }
  177. return str;
  178. }
  179. #endregion
  180. #region list转换成JSON
  181. /// <summary>
  182. /// list转换为Json
  183. /// </summary>
  184. /// <typeparam name="T"></typeparam>
  185. /// <param name="list"></param>
  186. /// <returns></returns>
  187. public static string ListToJson<T>(IList<T> list)
  188. {
  189. object obj = list[0];
  190. return ListToJson<T>(list, obj.GetType().Name);
  191. }
  192. /// <summary>
  193. /// list转换为json
  194. /// </summary>
  195. /// <typeparam name="T1"></typeparam>
  196. /// <param name="list"></param>
  197. /// <param name="p"></param>
  198. /// <returns></returns>
  199. private static string ListToJson<T>(IList<T> list, string JsonName)
  200. {
  201. StringBuilder Json = new StringBuilder();
  202. if (string.IsNullOrEmpty(JsonName))
  203. JsonName = list[0].GetType().Name;
  204. Json.Append("{\"" + JsonName + "\":[");
  205. if (list.Count > 0)
  206. {
  207. for (int i = 0; i < list.Count; i++)
  208. {
  209. T obj = Activator.CreateInstance<T>();
  210. PropertyInfo[] pi = obj.GetType().GetProperties();
  211. Json.Append("{");
  212. for (int j = 0; j < pi.Length; j++)
  213. {
  214. Type type = pi[j].GetValue(list[i], null).GetType();
  215. Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
  216. if (j < pi.Length - 1)
  217. {
  218. Json.Append(",");
  219. }
  220. }
  221. Json.Append("}");
  222. if (i < list.Count - 1)
  223. {
  224. Json.Append(",");
  225. }
  226. }
  227. }
  228. Json.Append("]}");
  229. return Json.ToString();
  230. }
  231. #endregion
  232. #region 对象转换为Json
  233. /// <summary>
  234. /// 对象转换为json
  235. /// </summary>
  236. /// <param name="jsonObject">json对象</param>
  237. /// <returns>json字符串</returns>
  238. public static string ToJson(object jsonObject)
  239. {
  240. string jsonString = "{";
  241. PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
  242. for (int i = 0; i < propertyInfo.Length; i++)
  243. {
  244. object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
  245. string value = string.Empty;
  246. if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
  247. {
  248. value = "'" + objectValue.ToString() + "'";
  249. }
  250. else if (objectValue is string)
  251. {
  252. value = "'" + ToJson(objectValue.ToString()) + "'";
  253. }
  254. else if (objectValue is IEnumerable)
  255. {
  256. value = ToJson((IEnumerable)objectValue);
  257. }
  258. else
  259. {
  260. value = ToJson(objectValue.ToString());
  261. }
  262. jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
  263. }
  264. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  265. return jsonString + "}";
  266. }
  267. #endregion
  268. #region 对象集合转换为json
  269. /// <summary>
  270. /// 对象集合转换为json
  271. /// </summary>
  272. /// <param name="array">对象集合</param>
  273. /// <returns>json字符串</returns>
  274. public static string ToJson(IEnumerable array)
  275. {
  276. string jsonString = "{";
  277. foreach (object item in array)
  278. {
  279. jsonString += ToJson(item) + ",";
  280. }
  281. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  282. return jsonString + "]";
  283. }
  284. #endregion
  285. #region 普通集合转换Json
  286. /// <summary>
  287. /// 普通集合转换Json
  288. /// </summary>
  289. /// <param name="array">集合对象</param>
  290. /// <returns>Json字符串</returns>
  291. public static string ToArrayString(IEnumerable array)
  292. {
  293. string jsonString = "[";
  294. foreach (object item in array)
  295. {
  296. jsonString = ToJson(item.ToString()) + ",";
  297. }
  298. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  299. return jsonString + "]";
  300. }
  301. #endregion
  302. #region DataSet转换为Json
  303. /// <summary>
  304. /// DataSet转换为Json
  305. /// </summary>
  306. /// <param name="dataSet">DataSet对象</param>
  307. /// <returns>Json字符串</returns>
  308. public static string ToJson(DataSet dataSet)
  309. {
  310. string jsonString = "{";
  311. foreach (DataTable table in dataSet.Tables)
  312. {
  313. jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
  314. }
  315. jsonString = jsonString.TrimEnd(',');
  316. return jsonString + "}";
  317. }
  318. #endregion
  319. #region Datatable转换为Json
  320. /// <summary>
  321. /// Datatable转换为Json
  322. /// </summary>
  323. /// <param name="table">Datatable对象</param>
  324. /// <returns>Json字符串</returns>
  325. public static string ToJson(DataTable dt)
  326. {
  327. StringBuilder jsonString = new StringBuilder();
  328. jsonString.Append("[");
  329. DataRowCollection drc = dt.Rows;
  330. for (int i = 0; i < drc.Count; i++)
  331. {
  332. jsonString.Append("{");
  333. for (int j = 0; j < dt.Columns.Count; j++)
  334. {
  335. string strKey = dt.Columns[j].ColumnName;
  336. string strValue = drc[i][j].ToString();
  337. Type type = dt.Columns[j].DataType;
  338. jsonString.Append("\"" + strKey + "\":");
  339. strValue = StringFormat(strValue, type);
  340. if (j < dt.Columns.Count - 1)
  341. {
  342. jsonString.Append(strValue + ",");
  343. }
  344. else
  345. {
  346. jsonString.Append(strValue);
  347. }
  348. }
  349. jsonString.Append("},");
  350. }
  351. jsonString.Remove(jsonString.Length - 1, 1);
  352. jsonString.Append("]");
  353. return jsonString.ToString();
  354. }
  355. /// <summary>
  356. /// DataTable转换为Json
  357. /// </summary>
  358. public static string ToJson(DataTable dt, string jsonName)
  359. {
  360. StringBuilder Json = new StringBuilder();
  361. if (string.IsNullOrEmpty(jsonName))
  362. jsonName = dt.TableName;
  363. Json.Append("{\"" + jsonName + "\":[");
  364. if (dt.Rows.Count > 0)
  365. {
  366. for (int i = 0; i < dt.Rows.Count; i++)
  367. {
  368. Json.Append("{");
  369. for (int j = 0; j < dt.Columns.Count; j++)
  370. {
  371. Type type = dt.Rows[i][j].GetType();
  372. Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
  373. if (j < dt.Columns.Count - 1)
  374. {
  375. Json.Append(",");
  376. }
  377. }
  378. Json.Append("}");
  379. if (i < dt.Rows.Count - 1)
  380. {
  381. Json.Append(",");
  382. }
  383. }
  384. }
  385. Json.Append("]}");
  386. return Json.ToString();
  387. }
  388. #endregion
  389. #region DataReader转换为Json
  390. /// <summary>
  391. /// DataReader转换为Json
  392. /// </summary>
  393. /// <param name="dataReader">DataReader对象</param>
  394. /// <returns>Json字符串</returns>
  395. public static string ToJson(DbDataReader dataReader)
  396. {
  397. StringBuilder jsonString = new StringBuilder();
  398. jsonString.Append("[");
  399. while (dataReader.Read())
  400. {
  401. jsonString.Append("{");
  402. for (int i = 0; i < dataReader.FieldCount; i++)
  403. {
  404. Type type = dataReader.GetFieldType(i);
  405. string strKey = dataReader.GetName(i);
  406. string strValue = dataReader[i].ToString();
  407. jsonString.Append("\"" + strKey + "\":");
  408. strValue = StringFormat(strValue, type);
  409. if (i < dataReader.FieldCount - 1)
  410. {
  411. jsonString.Append(strValue + ",");
  412. }
  413. else
  414. {
  415. jsonString.Append(strValue);
  416. }
  417. }
  418. jsonString.Append("},");
  419. }
  420. dataReader.Close();
  421. jsonString.Remove(jsonString.Length - 1, 1);
  422. jsonString.Append("]");
  423. return jsonString.ToString();
  424. }
  425. #endregion
  426. }
  427. }