关键词搜索

源码搜索 ×
×

C#中的DataSet、string、DataTable 、对象转换成Json

发布2015-01-12浏览1655次

详情内容

  1. /// <summary>
  2. /// 提供方法将其他类型转换为Json
  3. /// </summary>
  4. public static class ConvertToJson
  5. {
  6. #region 私有方法
  7. /// <summary>
  8. /// 过滤特殊字符
  9. /// </summary>
  10. /// <param name="s">字符串</param>
  11. /// <returns>json字符串</returns>
  12. private static string String2Json(String s)
  13. {
  14. StringBuilder sb = new StringBuilder();
  15. for (int i = 0; i < s.Length; i++)
  16. {
  17. char c = s.ToCharArray()[i];
  18. switch (c)
  19. {
  20. case '\"':
  21. sb.Append("\\\""); break;
  22. case '\\':
  23. sb.Append("\\\\"); break;
  24. case '/':
  25. sb.Append("\\/"); break;
  26. case '\b':
  27. sb.Append("\\b"); break;
  28. case '\f':
  29. sb.Append("\\f"); break;
  30. case '\n':
  31. sb.Append("\\n"); break;
  32. case '\r':
  33. sb.Append("\\r"); break;
  34. case '\t':
  35. sb.Append("\\t"); break;
  36. default:
  37. sb.Append(c); break;
  38. }
  39. }
  40. return sb.ToString();
  41. }
  42. /// <summary>
  43. /// 格式化字符型、日期型、布尔型
  44. /// </summary>
  45. /// <param name="str"></param>
  46. /// <param name="type"></param>
  47. /// <returns></returns>
  48. private static string StringFormat(string str, Type type)
  49. {
  50. if (type == typeof(string))
  51. {
  52. str = String2Json(str);
  53. str = "\"" + str + "\"";
  54. }
  55. else if (type == typeof(DateTime))
  56. {
  57. str = "\"" + str + "\"";
  58. }
  59. else if (type == typeof(bool))
  60. {
  61. str = str.ToLower();
  62. }
  63. else if (type != typeof(string) && string.IsNullOrEmpty(str))
  64. {
  65. str = "\"" + str + "\"";
  66. }
  67. return str;
  68. }
  69. #endregion
  70. #region list转换成JSON
  71. /// <summary>
  72. /// list转换为Json
  73. /// </summary>
  74. /// <typeparam name="T"></typeparam>
  75. /// <param name="list"></param>
  76. /// <returns></returns>
  77. public static string ListToJson<T>(IList<T> list)
  78. {
  79. object obj = list[0];
  80. return ListToJson<T>(list, obj.GetType().Name);
  81. }
  82. /// <summary>
  83. /// list转换为json
  84. /// </summary>
  85. /// <typeparam name="T"></typeparam>
  86. /// <param name="list"></param>
  87. /// <param name="JsonName"></param>
  88. /// <returns></returns>
  89. private static string ListToJson<T>(IList<T> list, string JsonName)
  90. {
  91. StringBuilder Json = new StringBuilder();
  92. if (string.IsNullOrEmpty(JsonName))
  93. JsonName = list[0].GetType().Name;
  94. Json.Append("{\"" + JsonName + "\":[");
  95. if (list.Count > 0)
  96. {
  97. for (int i = 0; i < list.Count; i++)
  98. {
  99. T obj = Activator.CreateInstance<T>();
  100. PropertyInfo[] pi = obj.GetType().GetProperties();
  101. Json.Append("{");
  102. for (int j = 0; j < pi.Length; j++)
  103. {
  104. Type type = pi[j].GetValue(list[i], null).GetType();
  105. Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
  106. if (j < pi.Length - 1)
  107. {
  108. Json.Append(",");
  109. }
  110. }
  111. Json.Append("}");
  112. if (i < list.Count - 1)
  113. {
  114. Json.Append(",");
  115. }
  116. }
  117. }
  118. Json.Append("]}");
  119. return Json.ToString();
  120. }
  121. #endregion
  122. #region 对象转换为Json
  123. /// <summary>
  124. /// 对象转换为json
  125. /// </summary>
  126. /// <param name="jsonObject">json对象</param>
  127. /// <returns>json字符串</returns>
  128. public static string ToJson(object jsonObject)
  129. {
  130. string jsonString = "{";
  131. PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
  132. for (int i = 0; i < propertyInfo.Length; i++)
  133. {
  134. object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
  135. string value = string.Empty;
  136. if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
  137. {
  138. value = "'" + objectValue.ToString() + "'";
  139. }
  140. else if (objectValue is string)
  141. {
  142. value = "'" + ToJson(objectValue.ToString()) + "'";
  143. }
  144. else if (objectValue is IEnumerable)
  145. {
  146. value = ToJson((IEnumerable)objectValue);
  147. }
  148. else
  149. {
  150. value = ToJson(objectValue.ToString());
  151. }
  152. jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
  153. }
  154. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  155. return jsonString + "}";
  156. }
  157. #endregion
  158. #region 对象集合转换为json
  159. /// <summary>
  160. /// 对象集合转换为json
  161. /// </summary>
  162. /// <param name="array">对象集合</param>
  163. /// <returns>json字符串</returns>
  164. public static string ToJson(IEnumerable array)
  165. {
  166. string jsonString = "{";
  167. foreach (object item in array)
  168. {
  169. jsonString += ToJson(item) + ",";
  170. }
  171. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  172. return jsonString + "]";
  173. }
  174. #endregion
  175. #region 普通集合转换Json
  176. /// <summary>
  177. /// 普通集合转换Json
  178. /// </summary>
  179. /// <param name="array">集合对象</param>
  180. /// <returns>Json字符串</returns>
  181. public static string ToArrayString(IEnumerable array)
  182. {
  183. string jsonString = "[";
  184. foreach (object item in array)
  185. {
  186. jsonString = ToJson(item.ToString()) + ",";
  187. }
  188. jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  189. return jsonString + "]";
  190. }
  191. #endregion
  192. #region DataSet转换为Json
  193. /// <summary>
  194. /// DataSet转换为Json
  195. /// </summary>
  196. /// <param name="dataSet">DataSet对象</param>
  197. /// <returns>Json字符串</returns>
  198. public static string ToJson(DataSet dataSet)
  199. {
  200. string jsonString = "{";
  201. foreach (DataTable table in dataSet.Tables)
  202. {
  203. jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
  204. }
  205. jsonString = jsonString.TrimEnd(',');
  206. return jsonString + "}";
  207. }
  208. #endregion
  209. #region Datatable转换为Json
  210. /// <summary>
  211. /// Datatable转换为Json
  212. /// </summary>
  213. /// <param name="dt">Datatable对象</param>
  214. /// <returns>Json字符串</returns>
  215. public static string ToJson(DataTable dt)
  216. {
  217. StringBuilder jsonString = new StringBuilder();
  218. jsonString.Append("[");
  219. DataRowCollection drc = dt.Rows;
  220. for (int i = 0; i < drc.Count; i++)
  221. {
  222. jsonString.Append("{");
  223. for (int j = 0; j < dt.Columns.Count; j++)
  224. {
  225. string strKey = dt.Columns[j].ColumnName;
  226. string strValue = drc[i][j].ToString();
  227. Type type = dt.Columns[j].DataType;
  228. jsonString.Append("\"" + strKey + "\":");
  229. strValue = StringFormat(strValue, type);
  230. if (j < dt.Columns.Count - 1)
  231. {
  232. jsonString.Append(strValue + ",");
  233. }
  234. else
  235. {
  236. jsonString.Append(strValue);
  237. }
  238. }
  239. jsonString.Append("},");
  240. }
  241. jsonString.Remove(jsonString.Length - 1, 1);
  242. jsonString.Append("]");
  243. return jsonString.ToString();
  244. }
  245. /// <summary>
  246. /// DataTable转换为Json
  247. /// </summary>
  248. public static string ToJson(DataTable dt, string jsonName)
  249. {
  250. StringBuilder Json = new StringBuilder();
  251. if (string.IsNullOrEmpty(jsonName))
  252. jsonName = dt.TableName;
  253. Json.Append("{\"" + jsonName + "\":[");
  254. if (dt.Rows.Count > 0)
  255. {
  256. for (int i = 0; i < dt.Rows.Count; i++)
  257. {
  258. Json.Append("{");
  259. for (int j = 0; j < dt.Columns.Count; j++)
  260. {
  261. Type type = dt.Rows[i][j].GetType();
  262. Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
  263. if (j < dt.Columns.Count - 1)
  264. {
  265. Json.Append(",");
  266. }
  267. }
  268. Json.Append("}");
  269. if (i < dt.Rows.Count - 1)
  270. {
  271. Json.Append(",");
  272. }
  273. }
  274. }
  275. Json.Append("]}");
  276. return Json.ToString();
  277. }
  278. #endregion
  279. #region DataReader转换为Json
  280. /// <summary>
  281. /// DataReader转换为Json
  282. /// </summary>
  283. /// <param name="dataReader">DataReader对象</param>
  284. /// <returns>Json字符串</returns>
  285. public static string ToJson(DbDataReader dataReader)
  286. {
  287. StringBuilder jsonString = new StringBuilder();
  288. jsonString.Append("[");
  289. while (dataReader.Read())
  290. {
  291. jsonString.Append("{");
  292. for (int i = 0; i < dataReader.FieldCount; i++)
  293. {
  294. Type type = dataReader.GetFieldType(i);
  295. string strKey = dataReader.GetName(i);
  296. string strValue = dataReader[i].ToString();
  297. jsonString.Append("\"" + strKey + "\":");
  298. strValue = StringFormat(strValue, type);
  299. if (i < dataReader.FieldCount - 1)
  300. {
  301. jsonString.Append(strValue + ",");
  302. }
  303. else
  304. {
  305. jsonString.Append(strValue);
  306. }
  307. }
  308. jsonString.Append("},");
  309. }
  310. dataReader.Close();
  311. jsonString.Remove(jsonString.Length - 1, 1);
  312. jsonString.Append("]");
  313. return jsonString.ToString();
  314. }
  315. #endregion
  316. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载