JsonHelper

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

 

posted @ 2012-11-08 14:59  Archosaur  Views(429)  Comments(0Edit  收藏  举报