1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Data.Common;
using System.Collections;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Json;
namespace System.Common
{
public static class Json
{
/// <summary>
/// List轉(zhuǎn)成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonName"></param>
/// <param name="list"></param>
/// <returns></returns>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type;
object o = pi[j].GetValue(list[i], null);
string v = string.Empty;
if (o != null)
{
type = o.GetType();
v = o.ToString();
}
else
{
type = typeof(string);
}
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(v, type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
/// <summary>
/// 序列化集合對(duì)象
/// </summary>
public static string JsonSerializerByArrayData<T>(T[] tArray)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T[]));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, tArray);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
/// <summary>
/// 序列化單個(gè)對(duì)象
/// </summary>
public static string JsonSerializerBySingleData<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
/// <summary>
/// 反序列化單個(gè)對(duì)象
/// </summary>
public static T JsonDeserializeBySingleData<T>(string jsonString)
{
//將"yyyy-MM-dd HH:mm:ss"格式的字符串轉(zhuǎn)為"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
/// <summary>
/// 反序列化集合對(duì)象
/// </summary>
public static T[] JsonDeserializeByArrayData<T>(string jsonString)
{
//將"yyyy-MM-dd HH:mm:ss"格式的字符串轉(zhuǎn)為"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T[]));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T[] arrayObj = (T[])ser.ReadObject(ms);
return arrayObj;
}
/// <summary>
/// 將Json序列化的時(shí)間由/Date(1294499956278+0800)轉(zhuǎn)為字符串
/// </summary>
private static string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
/// <summary>
/// 將時(shí)間字符串轉(zhuǎn)為Json時(shí)間
/// </summary>
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
return result;
}
/// <summary>
/// List轉(zhuǎn)成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[0];
return ListToJson<T>(list, obj.GetType().Name);
}
/// <summary>
/// 對(duì)象轉(zhuǎn)換為Json字符串
/// </summary>
/// <param name="jsonObject">對(duì)象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
try
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("{");
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
if (objectValue == null)
{
continue;
}
StringBuilder value = new StringBuilder();
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value.Append("\"" + objectValue.ToString() + "\"");
}
else if (objectValue is string)
{
value.Append("\"" + objectValue.ToString() + "\"");
}
else if (objectValue is IEnumerable)
{
value.Append(ToJson((IEnumerable)objectValue));
}
else
{
value.Append("\"" + objectValue.ToString() + "\"");
}
jsonString.Append("\"" + propertyInfo[i].Name + "\":" + value + ","); ;
}
return jsonString.ToString().TrimEnd(',') + "}";
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 對(duì)象集合轉(zhuǎn)換Json
/// </summary>
/// <param name="array">集合對(duì)象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += ToJson(item) + ",";
}
if (jsonString.Length > 1)
{
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
}
else
{
jsonString = "[]";
}
return jsonString + "]";
}
/// <summary>
/// 普通集合轉(zhuǎn)換Json
/// </summary>
/// <param name="array">集合對(duì)象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
/// <summary>
/// Datatable轉(zhuǎn)換為Json
/// </summary>
/// <param name="table">Datatable對(duì)象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
if (jsonString.Length == 1)
{
return "[]";
}
return jsonString.ToString();
}
/// <summary>
/// DataTable轉(zhuǎn)成Json
/// </summary>
/// <param name="jsonName"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(DataTable dt, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = dt.TableName;
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j] is DBNull ? string.Empty : dt.Rows[i][j].ToString(), type));
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
/// <summary>
/// DataReader轉(zhuǎn)換為Json
/// </summary>
/// <param name="dataReader">DataReader對(duì)象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IDataReader dataReader)
{
try
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
while (dataReader.Read())
{
jsonString.Append("{");
for (int i = 0; i < dataReader.FieldCount; i++)
{
Type type = dataReader.GetFieldType(i);
string strKey = dataReader.GetName(i);
string strValue = dataReader[i].ToString();
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (i < dataReader.FieldCount - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
if (!dataReader.IsClosed)
{
dataReader.Close();
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
if (jsonString.Length == 1)
{
return "[]";
}
return jsonString.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// DataSet轉(zhuǎn)換為Json
/// </summary>
/// <param name="dataSet">DataSet對(duì)象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
/// <summary>
/// 過(guò)濾特殊字符
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
case '\v':
sb.Append("\\v"); break;
case '\0':
sb.Append("\\0"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary>
/// 格式化字符型、日期型、布爾型
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
private static string StringFormat(string str, Type type)
{
if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
else if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type == typeof(byte[]))
{
str = "\"" + str + "\"";
}else if(type==typeof(Guid))
{
str = "\"" + str + "\"";
}
return str;
}
public static void RegistAjax(HtmlHead Header, Type type)
{
string assemblyName = type.FullName + "," + type.Assembly.FullName.Substring(0, type.Assembly.FullName.IndexOf(","));
if (type.Assembly.FullName.StartsWith("App_Code."))
{
assemblyName = type.FullName + ",App_Code";
}
Literal l = new Literal();
l.Text = "\n<script type=\"text/javascript\" src=\"/ajaxpro/prototype.ashx\"></script>\n"
+ "<script type=\"text/javascript\" src=\"/ajaxpro/core.ashx\"></script>\n"
+ "<script type=\"text/javascript\" src=\"/ajaxpro/converter.ashx\"></script>\n"
+ "<script type=\"text/javascript\" src=\"/ajaxpro/" + assemblyName + ".ashx\"></script>\n";
Header.Controls.Add(l);
}
}
}