jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/*------------------------------------------------------------------
-- COPYRIGHT (C) 2011-2020  hanhe
-- ALL RIGHTS RESERVED.
-- han he
-- CREATE DATE: 2014/06/27
-- CREATE MAN:    姜新军
-- 对象与JSON字符串互相转化类
-- MODIFY HISTORY:
-- MODIFY DATE:
-- MODIFY MAN:    
-- MODIFY DESC:
-- MODIFY DATE:
-- MODIFY MAN:    
-- MODIFY DESC:
---------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;
using System.Reflection;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;///记得引用这个命名空间
 
 
namespace HH.WMS.Common
{
    /// <summary>
    /// json类库
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 实例化
        /// </summary>
        public JsonHelper()
        {
        }
 
        #region 把DataTable数据,转化成JSON字符串
        /// <summary>
        /// 把DataTable数据,转化成JSON字符串
        /// </summary>
        /// <param name="jsonName">对象名称</param>
        /// <param name="dt">DataTable数据集</param>
        /// <returns>JSON数组字符串</returns>
        public static string DataTableToJson(string jsonName, DataTable dt, int total)
        {
            StringBuilder Json = new StringBuilder();
 
            if (!string.IsNullOrEmpty(jsonName))
            {
                Json.Append("{\"" + jsonName + "\":[");
            }
            else
            {
                if (total > 0)
                {
                    Json.Append("[");
                }
            }
 
            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++)
                    {
                        string key = dt.Columns[j].ColumnName.ToString();
                        string value = dt.Rows[i][j].ToString().Trim();
                        //DateTime dts = DateTime.Now;
                        if (Util.IsTDateTime(value))
                        {
                            value = DateTime.Parse(value).ToString("yyyy-MM-dd");
                        }
                        Json.Append("\"" + key + "\":\"" + value.Replace("\"","”") + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
 
            if (!string.IsNullOrEmpty(jsonName))
            {
                Json.Append("],");
                Json.Append("\"total\":" + total + "");
                Json.Append("}");
            }
            else
            {
                if (total > 0)
                {
                    Json.Append("]");
                }
            }
            return Json.ToString();
        }
 
 
 
        /// <summary>
        /// 把DataTable数据,转化成JSON字符串
        /// </summary>
        /// <param name="jsonName">对象名称</param>
        /// <param name="dt">DataTable数据集</param>
        /// <param name="pageCount">总页数</param>
        /// <param name="totalRecord">总记录数</param>
        /// <returns>JSON数组字符串</returns>
        public static string DataTableToJson(string jsonName, DataTable dt, int pageCount, int totalRecord)
        {
            StringBuilder Json = new StringBuilder();
 
            if (!string.IsNullOrEmpty(jsonName))
            {
                Json.Append("{\"" + jsonName + "\":[");
            }
            else
            {
                if (totalRecord > 0)
                {
                    Json.Append("[");
                }
            }
 
            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++)
                    {
                        string key = dt.Columns[j].ColumnName.ToString();
                        string value = dt.Rows[i][j].ToString().Trim();
                        //DateTime dts = DateTime.Now;
                        if (Util.IsTDateTime(value))
                        {
                            value = DateTime.Parse(value).ToString("yyyy-MM-dd");
                        }
                        Json.Append("\"" + key + "\":\"" + value + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
 
            if (!string.IsNullOrEmpty(jsonName))
            {
                Json.Append("],");
                Json.Append("\"total\":" + totalRecord + ",\"pagecount\":" + pageCount + "");
                Json.Append("}");
            }
            else
            {
                if (totalRecord > 0)
                {
                    Json.Append("]");
                }
            }
            return Json.ToString();
        }
        #endregion
 
        #region 把JSON字符串转化为DataTable
        /// <summary>
        /// Json 字符串 转换为 DataTable数据集合
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string jsonString)
        {
            DataTable dataTable = new DataTable();  //实例化
            try
            {
                ArrayList arrayList = JsonConvert.DeserializeObject<ArrayList>(jsonString);
                if (arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count<string>() == 0)
                        {
                            return dataTable;
                        }
                        //Columns
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (string current in dictionary.Keys)
                            {
                                dataTable.Columns.Add(current, dictionary[current].GetType());
                            }
                        }
                        //Rows
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            dataRow[current] = dictionary[current];
                        }
                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                    }
                }
            }
            catch
            {
            }
            return dataTable;
        }
        #endregion
 
        #region 把LIST数据对象,转化成JSON数组字符串
        /// <summary>
        /// 把LIST数据对象,转化成JSON数组字符串
        /// </summary>
        /// <typeparam name="IL">对象集合</typeparam>
        /// <param name="jsonName">JSON名称</param> 
        /// <returns>JSON数组字符串</returns>
        public static string IListToJson<T>(string jsonName, IList<T> IL, long totalRows)
        {
            StringBuilder Json = new StringBuilder();
            if (!string.IsNullOrEmpty(jsonName))
            {
                Json.Append("{\"" + jsonName + "\":[");
            }
            else
            {
                Json.Append("[");
            }
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        object value = pis[j].GetValue(IL[i], null);
                        //处理日期类型
                        if (Util.IsTDateTime(value))
                        {
                            //格式化日期
                            value = Util.ToString(Convert.ToDateTime(value), "yyyy-MM-dd HH:mm:ss");
                            //格式化成JSON日期。
                            string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
                            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
                            Regex reg = new Regex(pattern);
                            value = reg.Replace(value.ToString(), matchEvaluator);
                        }
                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + value + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
 
            if (!string.IsNullOrEmpty(jsonName))
            {
                if (totalRows >= 0)
                {
                    Json.Append("],\"total\":\"" + totalRows + "\"}");
                }
                else
                {
                    Json.Append("]}");
 
                }
            }
            else
            {
                Json.Append("]");
            }
 
            return Json.ToString();
        }
 
        /// <summary>
        /// 把LIST数据对象,转化成JSON数组字符串
        /// </summary>
        /// <typeparam name="IL">对象集合</typeparam>
        /// <param name="jsonName">JSON名称</param> 
        /// <param name="totalRows">总记录数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>JSON数组字符串</returns>
        public static string IListToJson<T>(string jsonName, IList<T> IL, long totalRows, long pageCount)
        {
            StringBuilder Json = new StringBuilder();
            if (!string.IsNullOrEmpty(jsonName))
            {
                Json.Append("{\"" + jsonName + "\":[");
            }
            else
            {
                Json.Append("[");
            }
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        object value = pis[j].GetValue(IL[i], null);
                        //处理日期类型
                        if (Util.IsTDateTime(value))
                        {
                            //格式化日期
                            value = Util.ToString(Convert.ToDateTime(value), "yyyy-MM-dd HH:mm:ss");
                            //格式化成JSON日期。
                            string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
                            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
                            Regex reg = new Regex(pattern);
                            value = reg.Replace(value.ToString(), matchEvaluator);
                        }
                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + value + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
 
            if (!string.IsNullOrEmpty(jsonName))
            {
                if (totalRows >= 0)
                {
                    Json.Append("],\"total\":\"" + totalRows + "\",\"pagecount\":\"" + pageCount + "\"}");
                }
                else
                {
                    Json.Append("]}");
 
                }
            }
            else
            {
                Json.Append("]");
            }
 
            return Json.ToString();
        }
        #endregion
 
        #region 把对象序列化 JSON 字符串
        /// <summary>
        /// 把对象序列化 JSON 字符串 
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象实体</param>
        /// <returns>JSON字符串</returns>
        public static string GetJson<T>(T obj)
        {
            //记住 添加引用 System.ServiceModel.Web 
            /**
             * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦
             * */
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                json.WriteObject(ms, obj);
                string szJson = Encoding.UTF8.GetString(ms.ToArray());
 
                return szJson;
            }
        }
        #endregion
 
        #region 把JSON字符串还原为对象
        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
 
                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
 
                return (T)dcj.ReadObject(ms);
 
 
            }
        }
        #endregion
 
        #region 将JSON字符串转换成对象集合
        /// <summary>
        /// 将JSON字符串转换成对象集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="JsonStr"></param>
        /// <returns></returns>
        public static List<T> JSONStringToList<T>(string JsonStr)
        {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            Serializer.MaxJsonLength = Int32.MaxValue;
            List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
            return objs;
        }
        #endregion
 
        #region 将Model对象转换成JsonString
        public static string ModelToJsonString<T>(T model)
        {
 
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = int.MaxValue;
            return serializer.Serialize(model);
        }
        #endregion
 
        #region 将json字符串转换为DataTable
        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns>返回datatable</returns>
        /// <history>[HanHe(ZMM)] CREATED 2017/10/12</history>
        public static DataTable JsonToDT(string strJson)
        {
            try
            {
                if (string.IsNullOrEmpty(strJson))
                {
                    return null;
                }
                //转换json格式
                strJson = strJson.Replace(",\"", "$$$\"").Replace("\":", "\"&&&").ToString();
                //取出表名   
                var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
                string strName = "test";// rg.Match(strJson).Value;
                DataTable tb = null;
                if (strJson.IndexOf("[") > -1)
                {
                    //去除表名   
                    strJson = strJson.Substring(strJson.IndexOf("[") + 1);
                }
                if (strJson.IndexOf("]") > -1)
                {
                    strJson = strJson.Substring(0, strJson.IndexOf("]"));
                }
 
                //获取数据   
                rg = new Regex(@"(?<={)[^}]+(?=})");
                MatchCollection mc = rg.Matches(strJson);
                for (int i = 0; i < mc.Count; i++)
                {
                    string strRow = mc[i].Value;
                    //string[] strRows = strRow.Split('*');
                    string[] strRows = strRow.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries);
                    //创建表   
                    if (tb == null)
                    {
                        tb = new DataTable();
                        tb.TableName = strName;
                        foreach (string str in strRows)
                        {
                            var dc = new DataColumn();
                            //string[] strCell = str.Split('#');
                            string[] strCell = str.Split(new string[] { "&&&" }, StringSplitOptions.RemoveEmptyEntries);
                            if (strCell[0].Substring(0, 1) == "\"")
                            {
                                int a = strCell[0].Length;
                                dc.ColumnName = strCell[0].Substring(1, a - 2);
                            }
                            else
                            {
                                dc.ColumnName = strCell[0];
                            }
                            tb.Columns.Add(dc);
                        }
                        tb.AcceptChanges();
                    }
 
                    //增加内容   
                    DataRow dr = tb.NewRow();
                    for (int r = 0; r < strRows.Length; r++)
                    {
                        //dr[r] = strRows[r].Split('#')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
                        dr[r] = strRows[r].Split(new string[] { "&&&" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
                    }
                    tb.Rows.Add(dr);
                    tb.AcceptChanges();
                }
 
                return tb; 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
 
        /// <summary>  
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串  
        /// </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>  
        /// 将时间字符串转为Json时间  
        /// </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>  
        /// 将时间字符串转为Json时间  
        /// </summary>  
        private static string ConvertDateStringToJsonDate(string DateTime)
        {
            string result = string.Empty;
            DateTime dt = Convert.ToDateTime(DateTime);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - Convert.ToDateTime("1970-01-01");
            result = string.Format("/Date({0}+0800)/", ts.TotalMilliseconds);
            return result;
        }
 
        /// <summary>
        /// 是否为日期+时间型字符串
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool IsTDateTime(string StrSource)
        {
            return Regex.IsMatch(StrSource, @"^(((((1[6-9]|[2-9]d)d{2})-(0?|1)-(0?[1-9]|d|3))|(((1[6-9]|[2-9]d)d{2})-(0?|1)-(0?[1-9]|d|30))|(((1[6-9]|[2-9]d)d{2})-0?2-(0?[1-9]|1d|2[0-8]))|(((1[6-9]|[2-9]d)(0||)|((16||)00))-0?2-29-)) (20|21|22|23|[0-1]?d):[0-5]?d:[0-5]?d)$ ");
        }
 
 
        /// <summary>
 
        /// Convert a List{T} to a DataTable.
 
        /// </summary>
 
        public static DataTable ToDataTable<T>(List<T> items)
        {
 
            var tb = new DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }
 
            foreach (T item in items)
            {
                var values = new object[props.Length];
                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                tb.Rows.Add(values);
            }
            return tb;
        }
 
 
 
        /// <summary>
 
        /// Determine of specified type is nullable
 
        /// </summary>
 
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
 
        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
 
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
 
            else
            {
                return t;
            }
        }
 
        public static string GetValue(string name)
        {
            try
            {
                var jsonFile = System.AppDomain.CurrentDomain.BaseDirectory + "\\Config.json";
                using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFile))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JObject o = (JObject)JToken.ReadFrom(reader);
                        var value = o[name].ToString();
                        return value.Replace("\r\n", "");
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Detail("获取json文件", "值timeSpan失败!原因:" + ex.Message);
                return "";
            }
 
        }
    }
}