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