在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本文实例讲述了C#实现集合转换成json格式数据的方法。分享给大家供大家参考,具体如下: /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToJson(DataTable dt) { if (dt != null && dt.Rows.Count > 0) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{\""); jsonBuilder.Append("data"); jsonBuilder.Append("\":["); for (int i = 0; i < dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("\""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("\":\""); jsonBuilder.Append(jsonStringFromat(dt.Rows[i][j].ToString())); jsonBuilder.Append("\","); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); jsonBuilder.Append("}"); return jsonBuilder.ToString(); } else { return ""; } } /// <summary> /// Enumerable转成JSON /// </summary> /// <param name="list"></param> /// <returns></returns> public static string EnumerableToJson(IEnumerable list) { StringBuilder json = new StringBuilder(); int i = 0; if (list != null) { json.Append("{\"data\":["); foreach (var item in list) { json.Append("{"); PropertyInfo[] pi = item.GetType().GetProperties(); int j = 0; foreach (var p in pi) { if (j < pi.Length - 1) { json.Append("\"" + p.Name.ToString() + "\":\"" + jsonStringFromat(p.GetValue(item, null).ToString()) + "\","); } else { json.Append("\"" + p.Name.ToString() + "\":\"" + jsonStringFromat(p.GetValue(item, null).ToString()) + "\""); } j++; } i++; json.Append("},"); } json.Remove(json.Length - 1, 1); json.Append("]}"); } if (i != 0) return json.ToString(); else return ""; }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论