DataSetToJson 扩展方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Common { public static class JsonExtensions { #region DataSetToJson 扩展方法 /// <summary> /// DataSetToJson 扩展方法 /// </summary> /// <param name="ds">要传入的DataSet</param> /// <param name="JsonName">Json的名称</param> /// <param name="ParName">Json字段名称</param> /// <returns>返回JSON字符串</returns> public static string DataSetToJson( this DataSet ds, string JsonName, string [] ParName) { try { if (ds == null ) { return "DataSet Is Null ,So I Can't Do It To Json!" ; } if (JsonName.Length < 1) { return "You Set The Json Name Is Wrong!" ; } if (ds.Tables[0].Columns.Count < ParName.Length) { return "You Give The ParName Is Bigger Than DataSet Columns!" ; } string josn = "{" + JsonName + ":[" ; string temp = "" ; for ( int j = 0; j < ds.Tables[0].Rows.Count; j++) { temp = temp + "{" ; for ( int i = 0; i < ParName.Length; i++) { temp += "" + ParName[i] + ":\'" + ds.Tables[0].Rows[j][ParName[i]] + "\'" ; if (i != ParName.Length - 1) { temp = temp + "," ; } } if (j == ds.Tables[0].Rows.Count - 1) { temp = temp + "}" ; } else { temp = temp + "}," ; } } josn = josn + temp + "]}" ; return josn; } catch (Exception ex) { return "Codeing is Error----" + ex.ToString(); } } #endregion #region DataSetToJson 扩展方法 /// <summary> /// DataSetToJson 扩展方法 /// </summary> /// <param name="ds">要传入的DataSet</param> /// <returns>返回JSON字符串<</returns> public static string DataSetToJson( this DataSet ds) { try { if (ds == null ) { return "DataSet Is Null ,So I Can't Do It To Json!" ; } string josn = "[" ; string temp = "" ; for ( int j = 0; j < ds.Tables[0].Rows.Count; j++) { temp = temp + "{" ; for ( int i = 0; i < ds.Tables[0].Columns.Count; i++) { temp += "" + ds.Tables[0].Columns[i].ColumnName + ":\'" + ds.Tables[0].Rows[j][i] + "\'" ; if (i != ds.Tables[0].Columns.Count - 1) { temp = temp + "," ; } } if (j == ds.Tables[0].Rows.Count - 1) { temp = temp + "}" ; } else { temp = temp + "}," ; } } josn = josn + temp + "]" ; return josn; } catch (Exception ex) { return "Codeing is Error----" + ex.ToString(); } } #endregion } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步