JsonHelp

  1 using Newtonsoft.Json;
  2 using Newtonsoft.Json.Converters;
  3 using Newtonsoft.Json.Linq;
  4 using System;
  5 using System.Collections;
  6 using System.Collections.Generic;
  7 using System.ComponentModel;
  8 using System.Reflection;
  9 using System.Text;
 10 using System.Linq;
 11 
 12 namespace Common
 13 {
 14     /// <summary>
 15     /// Json帮助类
 16     /// </summary>
 17     public static partial class JsonHelp
 18     {
 19         /// <summary>
 20         /// Json字符串转换为实体集合
 21         /// </summary>
 22         /// <typeparam name="T">实体类</typeparam>
 23         /// <param name="json">Json字符串</param>
 24         /// <returns>实体集合</returns>
 25         public static T ConvertJsonToEntity<T>(string json) where T : class
 26         {
 27             return JsonConvert.DeserializeObject<T>(json);
 28         }
 29 
 30         /// <summary>
 31         /// Json字符串转换为实体集合
 32         /// </summary>
 33         /// <typeparam name="T">实体类</typeparam>
 34         /// <param name="json">Json字符串</param>
 35         /// <returns>added对应新增实体集合;deleted对应删除实体集合;modified对应更新实体集合</returns>
 36         public static Dictionary<string, IEnumerable<T>> ConvertJsonToEntities<T>(string json) where T : new()
 37         {
 38             Dictionary<string, IEnumerable<T>> _return = new Dictionary<string, IEnumerable<T>>();
 39             IList<T> added = new List<T>();
 40             IList<T> deleted = new List<T>();
 41             IList<T> modified = new List<T>();
 42             ArrayList _c = MiniUIJson.Decode(json) as ArrayList;
 43             foreach (Hashtable row in _c)
 44             {
 45                 T t = new T();
 46                 PropertyInfo[] p = typeof(T).GetProperties();
 47                 foreach (var item in p)
 48                 {
 49                     string _temp = (row[item.Name] ?? string.Empty).ToString();
 50                     if (item.PropertyType.ToString().Contains(@"System.Int32"))
 51                     {
 52                         if (_temp == string.Empty) continue;
 53                         item.SetValue(t, Convert.ToInt32(_temp));
 54                     }
 55                     else if (item.PropertyType.ToString().Contains(@"System.Int16"))
 56                     {
 57                         if (_temp == string.Empty) continue;
 58                         item.SetValue(t, Convert.ToInt16(_temp));
 59                     }
 60                     else if (item.PropertyType.ToString().Contains(@"System.Byte[]"))
 61                     {
 62                         if (_temp == string.Empty) continue;
 63                         item.SetValue(t, Encoding.Default.GetBytes(_temp));
 64                     }
 65                     else if (item.PropertyType.ToString().Contains(@"System.Byte"))
 66                     {
 67                         if (_temp == string.Empty) continue;
 68                         item.SetValue(t, Convert.ToByte(_temp));
 69                     }
 70                     else if (item.PropertyType.ToString().Contains(@"System.Decimal"))
 71                     {
 72                         if (_temp == string.Empty) continue;
 73                         if (_temp == "null") continue;
 74                         item.SetValue(t, Convert.ToDecimal(_temp));
 75                     }
 76                     else if (item.PropertyType.ToString().Contains(@"System.DateTime"))
 77                     {
 78                         if (_temp == string.Empty) continue;
 79                         item.SetValue(t, Convert.ToDateTime(_temp));
 80                     }
 81                     else if (item.PropertyType.ToString().Contains(@"System.Boolean"))
 82                     {
 83                         if (_temp == string.Empty) continue;
 84                         item.SetValue(t, Convert.ToBoolean(_temp));
 85                     }
 86                     else if (item.PropertyType.ToString().Contains(@"System.Double"))
 87                     {
 88                         if (_temp == string.Empty) continue;
 89                         item.SetValue(t, Convert.ToDouble(_temp));
 90                     }
 91                     else if (item.PropertyType.ToString().Contains(@"CPPEI.Model"))
 92                     {
 93                         continue;
 94                     }
 95                     else if (item.PropertyType.ToString().Contains(@"System.Guid"))
 96                     {
 97                         if (_temp == string.Empty) continue;
 98                         item.SetValue(t, Guid.Parse(_temp));
 99                     }
100                     else
101                     {
102                         item.SetValue(t, Convert.ChangeType(row[item.Name], item.PropertyType));
103                     }
104                 }
105                 String state = (row["_state"] ?? string.Empty).ToString();
106                 switch (state.ToLower())
107                 {
108                     case "added":
109                         added.Add(t);
110                         break;
111                     case "removed":
112                         deleted.Add(t);
113                         break;
114                     case "deleted":
115                         deleted.Add(t);
116                         break;
117                     case "":
118                     case "modified":
119                         modified.Add(t);
120                         break;
121                     default:
122                         break;
123                 }
124             }
125             _return.Add("added", added);
126             _return.Add("deleted", deleted);
127             _return.Add("modified", modified);
128             return _return;
129         }
130 
131         /// <summary>
132         /// Json字符串转换为实体集合
133         /// </summary>
134         /// <typeparam name="T">实体类</typeparam>
135         /// <param name="_json">Json字符串</param>
136         /// <returns>added对应新增实体集合;deleted对应删除实体集合;modified对应更新实体集合</returns>
137         public static Dictionary<string, IEnumerable<T>> JsonToEntities<T>(string _json) where T : new()
138         {
139             if (string.IsNullOrWhiteSpace(_json))
140                 return null;
141             Dictionary<string, IEnumerable<T>> _list = new Dictionary<string, IEnumerable<T>>();
142             IList<T> added = new List<T>();
143             IList<T> deleted = new List<T>();
144             IList<T> modified = new List<T>();
145             object _r = JsonConvert.DeserializeObject(_json);
146             if (_r is IEnumerable<JToken>)
147             {
148                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
149                 {
150                     Hashtable ht = new Hashtable();
151                     foreach (KeyValuePair<string, JToken> _k in _i)
152                     {
153                         #region 循环属性
154                         if (typeof(JValue) == _k.Value.GetType())
155                         {
156                             object _m = (_k.Value as JValue).Value;
157                             if (_m != null)
158                             {
159                                 //判断是否符合2010-09-02T10:00:00的格式
160                                 string s = _m.ToString();
161                                 if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':')
162                                 {
163                                     ht[_k.Key] = Convert.ToDateTime(s);
164                                 }
165                                 else
166                                 {
167                                     ht[_k.Key] = s;
168                                 }
169                             }
170                         }
171                         #endregion
172                     }
173                     T t = new T();
174                     foreach (var item in typeof(T).GetProperties())
175                     {
176                         if (!item.GetGetMethod().IsVirtual && ht[item.Name] != null)
177                         {
178                             if (ht[item.Name].ToString() == string.Empty && item.PropertyType.Name != @"String")
179                             {
180                                 string[] _ijk = { "Int32", "Int16", "Byte", "Decimal", "Double", "Single" };
181                                 if (_ijk.Contains(item.PropertyType.Name) || _ijk.Contains(item.PropertyType.GenericTypeArguments[0].Name))
182                                 {
183                                     ht[item.Name] = 0;
184                                 }
185                             }
186                             item.SetValue(t, ChangeType(ht[item.Name], item.PropertyType));
187                         }
188                     }
189                     switch ((ht["_state"] ?? string.Empty).ToString())
190                     {
191                         case "added":
192                             added.Add(t);
193                             break;
194                         case "removed":
195                         case "deleted":
196                             deleted.Add(t);
197                             break;
198                         case "":
199                         case "modified":
200                             modified.Add(t);
201                             break;
202                         default:
203                             break;
204                     }
205                 }
206             }
207             _list.Add("added", added);
208             _list.Add("deleted", deleted);
209             _list.Add("modified", modified);
210             return _list;
211         }
212 
213         /// <summary>
214         /// 输入JSON,返回HASH集合
215         /// </summary>
216         /// <param name="_json">json字符串</param>
217         /// <returns>参数集合</returns>
218         public static IEnumerable<Hashtable> JsonToIEnumerable(string _json)
219         {
220             if (string.IsNullOrWhiteSpace(_json))
221                 return null;
222             IList<Hashtable> _list = new List<Hashtable>();
223             object _r = JsonConvert.DeserializeObject(_json);
224             if (_r is IEnumerable<JToken>)
225             {
226                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
227                 {
228                     Hashtable ht = new Hashtable();
229                     foreach (KeyValuePair<string, JToken> _k in _i)
230                     {
231                         #region 循环属性
232                         if (typeof(JValue) == _k.Value.GetType())
233                         {
234                             object _m = (_k.Value as JValue).Value;
235                             if (_m != null)
236                             {
237                                 //判断是否符合2010-09-02T10:00:00的格式
238                                 string s = _m.ToString();
239                                 if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':')
240                                 {
241                                     ht[_k.Key] = Convert.ToDateTime(s);
242                                 }
243                                 else
244                                 {
245                                     ht[_k.Key] = s;
246                                 }
247                             }
248                         }
249                         #endregion
250                     }
251                     _list.Add(ht);
252                 }
253             }
254             return _list;
255         }
256 
257         /// <summary>
258         /// 输入JSON,返回字典
259         /// </summary>
260         /// <param name="_json">json字符串</param>
261         /// <returns>参数集合</returns>
262         public static Dictionary<string, string> JsonToDictionary(string _json)
263         {
264             if (string.IsNullOrWhiteSpace(_json))
265                 return null;
266             Dictionary<string, string> _list = new Dictionary<string, string>();
267             object _r = JsonConvert.DeserializeObject(_json);
268             if (_r is IEnumerable<JToken>)
269             {
270                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
271                 {
272                     foreach (KeyValuePair<string, JToken> _k in _i)
273                     {
274                         #region 循环属性
275                         if (typeof(JValue) == _k.Value.GetType())
276                         {
277                             object _m = (_k.Value as JValue).Value;
278                             if (_m != null)
279                             {
280                                 //判断是否符合2010-09-02T10:00:00的格式
281                                 string s = _m.ToString();
282                                 if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':')
283                                 {
284                                     _list.Add(_k.Key, Convert.ToDateTime(s).ToString());
285                                 }
286                                 else
287                                 {
288                                     _list.Add(_k.Key, _k.Value.ToString());
289                                 }
290                             }
291                         }
292                         #endregion
293                     }
294                 }
295             }
296             return _list;
297         }
298 
299         /// <summary>
300         /// 输入JSON,返回字典
301         /// </summary>
302         /// <param name="_json">json字符串</param>
303         /// <returns>参数集合</returns>
304         public static IEnumerable<KeyValuePair<string, string>> JsonToIEDictionary(string _json)
305         {
306             if (string.IsNullOrWhiteSpace(_json))
307                 return null;
308             IList<KeyValuePair<string, string>> _list = new List<KeyValuePair<string, string>>();
309             object _r = JsonConvert.DeserializeObject(_json);
310             if (_r is IEnumerable<JToken>)
311             {
312                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
313                 {
314                     foreach (KeyValuePair<string, JToken> _k in _i)
315                     {
316                         #region 循环属性
317                         if (typeof(JValue) == _k.Value.GetType())
318                         {
319                             object _m = (_k.Value as JValue).Value;
320                             if (_m != null)
321                             {
322                                 //判断是否符合2010-09-02T10:00:00的格式
323                                 string s = _m.ToString();
324                                 if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':')
325                                 {
326                                     _list.Add(new KeyValuePair<string, string>(_k.Key, Convert.ToDateTime(s).ToString()));
327                                 }
328                                 else
329                                 {
330                                     _list.Add(new KeyValuePair<string, string>(_k.Key, _k.Value.ToString()));
331                                 }
332                             }
333                         }
334                         #endregion
335                     }
336                 }
337             }
338             return _list;
339         }
340 
341         /// <summary>
342         /// 实体对象转换为字符串
343         /// </summary>
344         /// <param name="o">实体对象</param>
345         /// <returns>字符串</returns>
346         public static string EntitiesToString(object o)
347         {
348             if (o == null || o.ToString() == "null") return null;
349 
350             if (o != null && (o.GetType() == typeof(String) || o.GetType() == typeof(string)))
351             {
352                 return o.ToString();
353             }
354             IsoDateTimeConverter dt = new IsoDateTimeConverter();
355             dt.DateTimeFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss";
356             return JsonConvert.SerializeObject(o, dt);
357         }
358 
359         /// <summary>
360         /// 类型转换
361         /// </summary>
362         /// <param name="value">数据</param>
363         /// <param name="targetType">类型</param>
364         /// <returns>数据类型</returns>
365         private static Object ChangeType(object value, Type targetType)
366         {
367             Type convertType = targetType;
368             if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
369             {
370                 NullableConverter nullableConverter = new NullableConverter(targetType);
371                 convertType = nullableConverter.UnderlyingType;
372             }
373             return Convert.ChangeType(value, convertType);
374         }
375 
376         /// <summary>
377         /// 类型转换
378         /// </summary>
379         /// <typeparam name="T">目标类型</typeparam>
380         /// <param name="convertibleValue">数据</param>
381         /// <returns>返回类型</returns>
382         public static T ConvertTo<T>(this IConvertible convertibleValue)
383         {
384             if (string.IsNullOrEmpty(convertibleValue.ToString()))
385             {
386                 return default(T);
387             }
388             if (!typeof(T).IsGenericType)
389             {
390                 return (T)Convert.ChangeType(convertibleValue, typeof(T));
391             }
392             else
393             {
394                 Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
395                 if (genericTypeDefinition == typeof(Nullable<>))
396                 {
397                     return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
398                 }
399             }
400             return default(T);
401         }
402 
403         /// <summary>
404         /// Hashtable转换为实体
405         /// </summary>
406         /// <typeparam name="T">实体类</typeparam>
407         /// <param name="t">实体类对象</param>
408         /// <param name="row">Hashtable数据源</param>
409         public static void ConvertHashToEntity<T>(T t, Hashtable row) where T : class
410         {
411             PropertyInfo[] p = typeof(T).GetProperties();
412 
413             foreach (var item in p)
414             {
415                 item.SetValue(t, ChangeType(row[item.Name], item.PropertyType), null);
416             }
417         }
418     }
419 }

 

转载于:https://www.cnblogs.com/qizhelongdeyang/p/JsonHelp%e7%b1%bb.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值