JSON格式互转集合

  在工作中我们经常会遇到格式转换的问题,有的时候是将JSON转换成DataTable、DataSet或是List等,也有可能将DataTable、DataSet或是List转换成JSON的,抽了点时间把这些方法整合了一下,希望对大家有所帮助,如果有什么问题请指出来,共同探讨。

代码:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Text;
  6 using System.Data;
  7 using System.Data.Common;
  8 using System.Collections;
  9 using System.Reflection;
 10 
 11 namespace BJYX.WEB.Public
 12 {
 13     public class Creat_Json
 14     {
 15         public Creat_Json()
 16         {
 17             //
 18             // TODO: 在此处添加构造函数逻辑
 19             //
 20         }
 21 
 22         public static string DataTable2Json(System.Data.DataTable dt)
 23         {
 24             System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
 25             jsonBuilder.Append("{");
 26             jsonBuilder.AppendFormat("\"total\":{0}, ", dt.Rows.Count);
 27             jsonBuilder.Append("\"rows\":[ ");
 28             for (int i = 0; i < dt.Rows.Count; i++)
 29             {
 30                 jsonBuilder.Append("{");
 31                 for (int j = 0; j < dt.Columns.Count; j++)
 32                 {
 33                     jsonBuilder.Append("\"");
 34                     jsonBuilder.Append(dt.Columns[j].ColumnName);
 35                     jsonBuilder.Append("\":\"");
 36                     jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("'", "&apos;").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>").Replace("\"", "&quot;"));
 37                     jsonBuilder.Append("\",");
 38                 }
 39                 jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
 40                 jsonBuilder.Append("},");
 41             }
 42             jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
 43             jsonBuilder.Append("]");
 44             jsonBuilder.Append("}");
 45             return jsonBuilder.ToString();
 46         }
 47         public static string DataTable2Json(System.Data.DataTable dt, int count)
 48         {
 49             System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
 50             jsonBuilder.Append("{");
 51             jsonBuilder.AppendFormat("\"total\":{0}, ", count);
 52             jsonBuilder.Append("\"rows\":[ ");
 53             for (int i = 0; i < dt.Rows.Count; i++)
 54             {
 55                 jsonBuilder.Append("{");
 56                 for (int j = 0; j < dt.Columns.Count; j++)
 57                 {
 58                     jsonBuilder.Append("\"");
 59                     jsonBuilder.Append(dt.Columns[j].ColumnName);
 60                     jsonBuilder.Append("\":\"");
 61                     jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("'", "&apos;").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>").Replace("\"", "&quot;"));
 62                     jsonBuilder.Append("\",");
 63                 }
 64                 jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
 65                 jsonBuilder.Append("},");
 66             }
 67             jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
 68             jsonBuilder.Append("]");
 69             jsonBuilder.Append("}");
 70             return jsonBuilder.ToString();
 71         }
 72         public static string DataTableToJson(System.Data.DataTable dt)
 73         {
 74             StringBuilder Json = new StringBuilder();
 75             Json.Append("[");
 76             if (dt.Rows.Count > 0)
 77             {
 78                 for (int i = 0; i < dt.Rows.Count; i++)
 79                 {
 80                     Json.Append("{");
 81                     for (int j = 0; j < dt.Columns.Count; j++)
 82                     {
 83                         Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("'", "&apos;").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>").Replace("\"", "&quot;") + "\"");
 84                         if (j < dt.Columns.Count - 1)
 85                         {
 86                             Json.Append(",");
 87                         }
 88                     }
 89                     Json.Append("}");
 90                     if (i < dt.Rows.Count - 1)
 91                     {
 92                         Json.Append(",");
 93                     }
 94                 }
 95             }
 96             Json.Append("]");
 97             return Json.ToString().Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>");//.Replace("\"", "'"); ;
 98         }
 99 
100         /// <summary>
101         /// Table to JSON By FlexGrid
102         /// </summary>
103         /// <param name="ds"></param>
104         /// <param name="page"></param>
105         /// <returns></returns>
106         public static string DataTableToJson(System.Data.DataTable dt, int page, int total)
107         {
108             StringBuilder jsonStr = new StringBuilder();
109             jsonStr.Append("{");
110             jsonStr.Append("\"page\":" + page + ",");
111             jsonStr.Append("\"total\":" + total + ",");
112             jsonStr.Append("\"rows\":");
113             jsonStr.Append("[");
114 
115             foreach (System.Data.DataRow dr in dt.Rows)
116             {
117                 jsonStr.Append("{");
118 
119                 foreach (System.Data.DataColumn dc in dt.Columns)
120                 {
121                     jsonStr.Append("\"");
122                     jsonStr.Append(dc.ColumnName);
123                     jsonStr.Append("\"");
124                     jsonStr.Append(":");
125 
126                     jsonStr.Append("\"");
127                     jsonStr.Append(dr[dc].ToString().Trim());
128                     jsonStr.Append("\" ,");
129                 }
130 
131                 jsonStr.Remove(jsonStr.Length - 1, 1);
132                 jsonStr.Append("}");
133                 jsonStr.Append(",");
134             }
135             if (dt.Rows.Count > 0)
136             {
137                 jsonStr.Remove(jsonStr.Length - 1, 1);
138             }
139             jsonStr.Append("]");
140             jsonStr.Append("}");
141 
142             return jsonStr.ToString();
143         }
144 
145         /// <summary>   
146         /// List转成json    
147         /// </summary>   
148         /// <typeparam name="T"></typeparam>   
149         /// <param name="jsonName"></param>   
150         /// <param name="list"></param>   
151         /// <returns></returns>   
152         public static string ListToJson<T>(IList<T> list, string jsonName)
153         {
154             StringBuilder Json = new StringBuilder();
155             if (string.IsNullOrEmpty(jsonName))
156                 jsonName = list[0].GetType().Name;
157             Json.Append("{\"" + jsonName + "\":[");
158             if (list.Count > 0)
159             {
160                 for (int i = 0; i < list.Count; i++)
161                 {
162                     T obj = Activator.CreateInstance<T>();
163                     PropertyInfo[] pi = obj.GetType().GetProperties();
164                     Json.Append("{");
165                     for (int j = 0; j < pi.Length; j++)
166                     {
167                         Type type = pi[j].GetValue(list[i], null).GetType();
168                         Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
169 
170                         if (j < pi.Length - 1)
171                         {
172                             Json.Append(",");
173                         }
174                     }
175                     Json.Append("}");
176                     if (i < list.Count - 1)
177                     {
178                         Json.Append(",");
179                     }
180                 }
181             }
182             Json.Append("]}");
183             return Json.ToString();
184         }
185 
186         /// <summary>   
187         /// List转成json    
188         /// </summary>   
189         /// <typeparam name="T"></typeparam>   
190         /// <param name="list"></param>   
191         /// <returns></returns>   
192         public static string ListToJson<T>(IList<T> list)
193         {
194             object obj = list[0];
195             return ListToJson<T>(list, obj.GetType().Name);
196         }
197 
198         /// <summary>    
199         /// 对象转换为Json字符串    
200         /// </summary>    
201         /// <param name="jsonObject">对象</param>    
202         /// <returns>Json字符串</returns>    
203         public static string ToJson(object jsonObject)
204         {
205             string jsonString = "{";
206             PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
207             for (int i = 0; i < propertyInfo.Length; i++)
208             {
209                 object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
210                 string value = string.Empty;
211                 if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
212                 {
213                     value = "'" + objectValue.ToString() + "'";
214                 }
215                 else if (objectValue is string)
216                 {
217                     value = "'" + ToJson(objectValue.ToString()) + "'";
218                 }
219                 else if (objectValue is IEnumerable)
220                 {
221                     value = ToJson((IEnumerable)objectValue);
222                 }
223                 else
224                 {
225                     value = ToJson(objectValue.ToString());
226                 }
227                 jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
228             }
229             jsonString.Remove(jsonString.Length - 1, jsonString.Length);
230             return jsonString + "}";
231         }
232 
233         /// <summary>    
234         /// 对象集合转换Json    
235         /// </summary>    
236         /// <param name="array">集合对象</param>    
237         /// <returns>Json字符串</returns>    
238         public static string ToJson(IEnumerable array)
239         {
240             string jsonString = "[";
241             foreach (object item in array)
242             {
243                 jsonString += ToJson(item) + ",";
244             }
245             jsonString.Remove(jsonString.Length - 1, jsonString.Length);
246             return jsonString + "]";
247         }
248 
249         /// <summary>    
250         /// 普通集合转换Json    
251         /// </summary>    
252         /// <param name="array">集合对象</param>    
253         /// <returns>Json字符串</returns>    
254         public static string ToArrayString(IEnumerable array)
255         {
256             string jsonString = "[";
257             foreach (object item in array)
258             {
259                 jsonString = ToJson(item.ToString()) + ",";
260             }
261             jsonString.Remove(jsonString.Length - 1, jsonString.Length);
262             return jsonString + "]";
263         }
264 
265         /// <summary>    
266         /// Datatable转换为Json    
267         /// </summary>    
268         /// <param name="table">Datatable对象</param>    
269         /// <returns>Json字符串</returns>    
270         public static string ToJson(DataTable dt)
271         {
272             StringBuilder jsonString = new StringBuilder();
273             jsonString.Append("[");
274             DataRowCollection drc = dt.Rows;
275             for (int i = 0; i < drc.Count; i++)
276             {
277                 jsonString.Append("{");
278                 for (int j = 0; j < dt.Columns.Count; j++)
279                 {
280                     string strKey = dt.Columns[j].ColumnName;
281                     string strValue = drc[i][j].ToString();
282                     Type type = dt.Columns[j].DataType;
283                     jsonString.Append("\"" + strKey + "\":");
284                     strValue = StringFormat(strValue, type);
285                     if (j < dt.Columns.Count - 1)
286                     {
287                         jsonString.Append(strValue + ",");
288                     }
289                     else
290                     {
291                         jsonString.Append(strValue);
292                     }
293                 }
294                 jsonString.Append("},");
295             }
296             jsonString.Remove(jsonString.Length - 1, 1);
297             jsonString.Append("]");
298             return jsonString.ToString();
299         }
300 
301         /// <summary>   
302         /// DataTable转成Json    
303         /// </summary>   
304         /// <param name="jsonName"></param>   
305         /// <param name="dt"></param>   
306         /// <returns></returns>   
307         public static string ToJson(DataTable dt, string jsonName)
308         {
309             StringBuilder Json = new StringBuilder();
310             if (string.IsNullOrEmpty(jsonName))
311                 jsonName = dt.TableName;
312             Json.Append("{\"" + jsonName + "\":[");
313             if (dt.Rows.Count > 0)
314             {
315                 for (int i = 0; i < dt.Rows.Count; i++)
316                 {
317                     Json.Append("{");
318                     for (int j = 0; j < dt.Columns.Count; j++)
319                     {
320                         Type type = dt.Rows[i][j].GetType();
321                         Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
322                         if (j < dt.Columns.Count - 1)
323                         {
324                             Json.Append(",");
325                         }
326                     }
327                     Json.Append("}");
328                     if (i < dt.Rows.Count - 1)
329                     {
330                         Json.Append(",");
331                     }
332                 }
333             }
334             Json.Append("]}");
335             return Json.ToString();
336         }
337 
338         /// <summary>    
339         /// DataReader转换为Json    
340         /// </summary>    
341         /// <param name="dataReader">DataReader对象</param>    
342         /// <returns>Json字符串</returns>    
343         public static string ToJson(DbDataReader dataReader)
344         {
345             StringBuilder jsonString = new StringBuilder();
346             jsonString.Append("[");
347             while (dataReader.Read())
348             {
349                 jsonString.Append("{");
350                 for (int i = 0; i < dataReader.FieldCount; i++)
351                 {
352                     Type type = dataReader.GetFieldType(i);
353                     string strKey = dataReader.GetName(i);
354                     string strValue = dataReader[i].ToString();
355                     jsonString.Append("\"" + strKey + "\":");
356                     strValue = StringFormat(strValue, type);
357                     if (i < dataReader.FieldCount - 1)
358                     {
359                         jsonString.Append(strValue + ",");
360                     }
361                     else
362                     {
363                         jsonString.Append(strValue);
364                     }
365                 }
366                 jsonString.Append("},");
367             }
368             dataReader.Close();
369             jsonString.Remove(jsonString.Length - 1, 1);
370             jsonString.Append("]");
371             return jsonString.ToString();
372         }
373         /// <summary>
374         /// 将IList转成JSON
375         /// </summary>
376         /// <typeparam name="T"></typeparam>
377         /// <param name="jsonName"></param>
378         /// <param name="IL"></param>
379         /// <returns></returns>
380         public static string ObjectToJson<T>(IList<T> IL)
381         {
382             StringBuilder Json = new StringBuilder();
383             Json.Append("[");
384             if (IL.Count > 0)
385             {
386                 for (int i = 0; i < IL.Count; i++)
387                 {
388                     T obj = Activator.CreateInstance<T>();
389                     Type type = obj.GetType();
390                     PropertyInfo[] pis = type.GetProperties();
391                     Json.Append("{");
392                     for (int j = 0; j < pis.Length; j++)
393                     {
394                         Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
395                         if (j < pis.Length - 1)
396                         {
397                             Json.Append(",");
398                         }
399                     }
400                     Json.Append("}");
401                     if (i < IL.Count - 1)
402                     {
403                         Json.Append(",");
404                     }
405                 }
406             }
407             Json.Append("]");
408             return Json.ToString();
409         }
410 
411         /// <summary>
412         /// 将IList转成符合FlexiGrid控件格式的JSON
413         /// </summary>
414         /// <typeparam name="T"></typeparam>
415         /// <param name="IL"></param>
416         /// <param name="page">但前页</param>
417         /// <param name="total">数据行数</param>
418         /// <returns></returns>
419         public static string ListToFlexiGridJson<T>(IList<T> IL, int page, int total)
420         {
421             StringBuilder Json = new StringBuilder();
422             Json.Append("{");
423             Json.Append("\"page\":" + page + ",");
424             Json.Append("\"total\":" + total + ",");
425             Json.Append("\"rows\":");
426             Json.Append("[");
427 
428             if (IL.Count > 0)
429             {
430                 for (int i = 0; i < IL.Count; i++)
431                 {
432                     T obj = Activator.CreateInstance<T>();
433                     Type type = obj.GetType();
434                     PropertyInfo[] pis = type.GetProperties();
435                     Json.Append("{");
436                     for (int j = 0; j < pis.Length; j++)
437                     {
438                         Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
439                         if (j < pis.Length - 1)
440                         {
441                             Json.Append(",");
442                         }
443                     }
444                     Json.Append("}");
445                     if (i < IL.Count - 1)
446                     {
447                         Json.Append(",");
448                     }
449                 }
450             }
451             Json.Append("]");
452             Json.Append("}");
453             return Json.ToString();
454         }
455 
456         /// <summary>    
457         /// DataSet转换为Json    
458         /// </summary>    
459         /// <param name="dataSet">DataSet对象</param>    
460         /// <returns>Json字符串</returns>    
461         public static string ToJson(DataSet dataSet)
462         {
463             string jsonString = "{";
464             foreach (DataTable table in dataSet.Tables)
465             {
466                 jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
467             }
468             jsonString = jsonString.TrimEnd(',');
469             return jsonString + "}";
470         }
471 
472         /// <summary>   
473         /// 过滤特殊字符   
474         /// </summary>   
475         /// <param name="s"></param>   
476         /// <returns></returns>   
477         private static string String2Json(String s)
478         {
479             StringBuilder sb = new StringBuilder();
480             for (int i = 0; i < s.Length; i++)
481             {
482                 char c = s.ToCharArray()[i];
483                 switch (c)
484                 {
485                     case '\"':
486                         sb.Append("\\\""); break;
487                     case '\\':
488                         sb.Append("\\\\"); break;
489                     case '/':
490                         sb.Append("\\/"); break;
491                     case '\b':
492                         sb.Append("\\b"); break;
493                     case '\f':
494                         sb.Append("\\f"); break;
495                     case '\n':
496                         sb.Append("\\n"); break;
497                     case '\r':
498                         sb.Append("\\r"); break;
499                     case '\t':
500                         sb.Append("\\t"); break;
501                     default:
502                         sb.Append(c); break;
503                 }
504             }
505             return sb.ToString();
506         }
507 
508         /// <summary>   
509         /// 格式化字符型、日期型、布尔型   
510         /// </summary>   
511         /// <param name="str"></param>   
512         /// <param name="type"></param>   
513         /// <returns></returns>   
514         private static string StringFormat(string str, Type type)
515         {
516             if (type == typeof(string))
517             {
518                 str = String2Json(str);
519                 str = "\"" + str + "\"";
520             }
521             else if (type == typeof(DateTime))
522             {
523                 str = "\"" + str + "\"";
524             }
525             else if (type == typeof(bool))
526             {
527                 str = str.ToLower();
528             }
529             return str;
530         }
531 
532 
533     }
534 }
View Code

 

posted @ 2016-02-19 13:59  zhangzhenpeng  阅读(1810)  评论(0编辑  收藏  举报