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

438 lines
17 KiB

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