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. && s[] == ] == ] == ':')
  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. ].Name))
  182. {
  183. ht[item.Name] = ;
  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. && s[] == ] == ] == ':')
  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. && s[] == ] == ] == ':')
  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. && s[] == ] == ] == ':')
  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. }

JsonHelp的更多相关文章

  1. 通用JSONHelp 的通用的封装

    1. 最近项目已经上线了 ,闲暇了几天 想将JSON  的序列化 以及反序列化进行重新的封装一下本人定义为JSONHelp,虽然Microsoft 已经做的很好了.但是我想封装一套为自己开发的项目使用 ...

  2. C# 对象数据转换Json帮助类 JsonHelp

    C# 对象数据转换Json帮助类 JsonHelp using System; using System.Data; using System.Configuration; using System. ...

  3. JSONHelp json解析成类,类解析成string

    using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization. ...

  4. Silverlight 使用DataContractJsonSerializer序列化与反序列化 Json

    环境说明:Silverlight 5.1,.Net Framework  ​4.0 1.添加引用System.ServiceModel.Web.dll. 因为 System.Runtime.Seria ...

  5. .net 实体类与json转换(.net自带类库实现)更新

    上一篇文章中写到在.net中实体类跟json格式的相互转换,今天在做具体转换时候,发现之前版本的jsonhelp对于日期类型的转换不全面.之前版本的jsonhelp中从实体类转换成json格式时候,将 ...

  6. .net 实体类与json转换(.net自带类库实现)

    注意要点. 1.jsonhelp编写时候添加的引用.System.Runtime.Serialization.Json; 2.实体类需声明为public jsonhelp代码: using Syste ...

  7. C#中JSON序列化和反序列化

    有一段时间没有到博客园写技术博客了,不过每天逛逛博客园中大牛的博客还是有的,学无止境…… 最近在写些调用他人接口的程序,用到了大量的JSON.XML序列化和反序列化,今天就来总结下json的序列化和反 ...

  8. 关于asp.net 开发的小技巧—让传值对象化

    前端:前端 定义一个对象, 传值时实例此对象,序列化成json字符串 代码如下: 定义js对象: ///定义一个查询条件对象 var SearchCondition=function(){ this. ...

  9. 微信授权步骤与详解 -- c#篇

    微信授权步骤与详解 -- c#篇 注:这里不涉及界面操作,只介绍代码操作. 1.基本原理如下: 从图上所知,第一步用户访问我们的网页,第二步我们后台跳转到微信授权页面,第三步用户点击授权,第四步微信重 ...

随机推荐

  1. 如何优雅的封装一个DOM事件库

    1.DOM0级事件和DOM2级事件 DOM 0级事件是元素内的一个私有属性:div.onclick = function () {},对一个私有属性赋值(在该事件上绑定一个方法).由此可知DOM 0级 ...

  2. Centos7 部署.netCore2.0项目

    最近在学习.netCore2.0,学习了在Centos上部署.netCore的方法,中间遇到过坑,特意贴出来供大家分享,在此我只是简单的在CentOS上运行.NETCore网站,没有运用到nginx等 ...

  3. 使用 Python 管理 Azure:基础配置

    Azure 提供了丰富的 Python SDK 来对 Azure 进行开发管理,包括使用 Azure 的开源框架在 Azure 上创建 web 应用程序,对 Azure 的虚拟机,存储等进行管理,本系 ...

  4. java——程序的导出与导入

    导出: 选择项目,右击选择 最下面的properties——Resource——Location,就是你的项目所在地, 找到文件所在,拷贝到你的U盘中(或者直接点击项目直接拖到桌面)完成复制 导入: ...

  5. SpringMVC 工作流程

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/baidu_36697353/article/details/64444147 SpringMVC 工 ...

  6. 弹性布局(flex)

    一.Flex 布局是什么? Flex 是 Flexible Box 的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性. 任何一个容器都可以指定为 Flex 布局.但在使用时 ...

  7. Java Struts2 (二)

    二.封装请求正文到对象中(非常重要) 1.静态参数封装 在struts.xml配置文件中,给动作类注入值.调用的是setter方法. 原因:是由一个staticParams的拦截器完成注入的. 2.动 ...

  8. Django—Cookie and Session

    一.Cookie Cookie,有时也用其复数形式 Cookies,指某些网站为了辨别用户身份.进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密). 1. 应用 服务器可以利用Co ...

  9. Android Studio图形基础(AS开发实战第二章学习笔记)

    图形基础 一.drawable 在代码中引用drawable文件可分为两种情况 (1)使用setBackgroundResource和setImageResource方法,可直接在参数中指定drawa ...

  10. 2 (自我拓展)部署花的识别模型(学习tensorflow实战google深度学习框架)

    kaggle竞赛的inception模型已经能够提取图像很好的特征,后续训练出一个针对当前图片数据的全连接层,进行花的识别和分类.这里见书即可,不再赘述. 书中使用google参加Kaggle竞赛的i ...