using Newtonsoft.Json;
 using Newtonsoft.Json.Converters;
 using Newtonsoft.Json.Linq;
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Reflection;
 using System.Text;
 using System.Linq;

 namespace Common
 {
     /// <summary>
     /// Json帮助类
     /// </summary>
     public static partial class JsonHelp
     {
         /// <summary>
         /// Json字符串转换为实体集合
         /// </summary>
         /// <typeparam name="T">实体类</typeparam>
         /// <param name="json">Json字符串</param>
         /// <returns>实体集合</returns>
         public static T ConvertJsonToEntity<T>(string json) where T : class
         {
             return JsonConvert.DeserializeObject<T>(json);
         }

         /// <summary>
         /// Json字符串转换为实体集合
         /// </summary>
         /// <typeparam name="T">实体类</typeparam>
         /// <param name="json">Json字符串</param>
         /// <returns>added对应新增实体集合;deleted对应删除实体集合;modified对应更新实体集合</returns>
         public static Dictionary<string, IEnumerable<T>> ConvertJsonToEntities<T>(string json) where T : new()
         {
             Dictionary<string, IEnumerable<T>> _return = new Dictionary<string, IEnumerable<T>>();
             IList<T> added = new List<T>();
             IList<T> deleted = new List<T>();
             IList<T> modified = new List<T>();
             ArrayList _c = MiniUIJson.Decode(json) as ArrayList;
             foreach (Hashtable row in _c)
             {
                 T t = new T();
                 PropertyInfo[] p = typeof(T).GetProperties();
                 foreach (var item in p)
                 {
                     string _temp = (row[item.Name] ?? string.Empty).ToString();
                     if (item.PropertyType.ToString().Contains(@"System.Int32"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Convert.ToInt32(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Int16"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Convert.ToInt16(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Byte[]"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Encoding.Default.GetBytes(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Byte"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Convert.ToByte(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Decimal"))
                     {
                         if (_temp == string.Empty) continue;
                         if (_temp == "null") continue;
                         item.SetValue(t, Convert.ToDecimal(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.DateTime"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Convert.ToDateTime(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Boolean"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Convert.ToBoolean(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Double"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Convert.ToDouble(_temp));
                     }
                     else if (item.PropertyType.ToString().Contains(@"CPPEI.Model"))
                     {
                         continue;
                     }
                     else if (item.PropertyType.ToString().Contains(@"System.Guid"))
                     {
                         if (_temp == string.Empty) continue;
                         item.SetValue(t, Guid.Parse(_temp));
                     }
                     else
                     {
                         item.SetValue(t, Convert.ChangeType(row[item.Name], item.PropertyType));
                     }
                 }
                 String state = (row["_state"] ?? string.Empty).ToString();
                 switch (state.ToLower())
                 {
                     case "added":
                         added.Add(t);
                         break;
                     case "removed":
                         deleted.Add(t);
                         break;
                     case "deleted":
                         deleted.Add(t);
                         break;
                     case "":
                     case "modified":
                         modified.Add(t);
                         break;
                     default:
                         break;
                 }
             }
             _return.Add("added", added);
             _return.Add("deleted", deleted);
             _return.Add("modified", modified);
             return _return;
         }

         /// <summary>
         /// Json字符串转换为实体集合
         /// </summary>
         /// <typeparam name="T">实体类</typeparam>
         /// <param name="_json">Json字符串</param>
         /// <returns>added对应新增实体集合;deleted对应删除实体集合;modified对应更新实体集合</returns>
         public static Dictionary<string, IEnumerable<T>> JsonToEntities<T>(string _json) where T : new()
         {
             if (string.IsNullOrWhiteSpace(_json))
                 return null;
             Dictionary<string, IEnumerable<T>> _list = new Dictionary<string, IEnumerable<T>>();
             IList<T> added = new List<T>();
             IList<T> deleted = new List<T>();
             IList<T> modified = new List<T>();
             object _r = JsonConvert.DeserializeObject(_json);
             if (_r is IEnumerable<JToken>)
             {
                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
                 {
                     Hashtable ht = new Hashtable();
                     foreach (KeyValuePair<string, JToken> _k in _i)
                     {
                         #region 循环属性
                         if (typeof(JValue) == _k.Value.GetType())
                         {
                             object _m = (_k.Value as JValue).Value;
                             if (_m != null)
                             {
                                 //判断是否符合2010-09-02T10:00:00的格式
                                 string s = _m.ToString();
                                  && s[] == ] == ] == ':')
                                 {
                                     ht[_k.Key] = Convert.ToDateTime(s);
                                 }
                                 else
                                 {
                                     ht[_k.Key] = s;
                                 }
                             }
                         }
                         #endregion
                     }
                     T t = new T();
                     foreach (var item in typeof(T).GetProperties())
                     {
                         if (!item.GetGetMethod().IsVirtual && ht[item.Name] != null)
                         {
                             if (ht[item.Name].ToString() == string.Empty && item.PropertyType.Name != @"String")
                             {
                                 string[] _ijk = { "Int32", "Int16", "Byte", "Decimal", "Double", "Single" };
                                 ].Name))
                                 {
                                     ht[item.Name] = ;
                                 }
                             }
                             item.SetValue(t, ChangeType(ht[item.Name], item.PropertyType));
                         }
                     }
                     switch ((ht["_state"] ?? string.Empty).ToString())
                     {
                         case "added":
                             added.Add(t);
                             break;
                         case "removed":
                         case "deleted":
                             deleted.Add(t);
                             break;
                         case "":
                         case "modified":
                             modified.Add(t);
                             break;
                         default:
                             break;
                     }
                 }
             }
             _list.Add("added", added);
             _list.Add("deleted", deleted);
             _list.Add("modified", modified);
             return _list;
         }

         /// <summary>
         /// 输入JSON,返回HASH集合
         /// </summary>
         /// <param name="_json">json字符串</param>
         /// <returns>参数集合</returns>
         public static IEnumerable<Hashtable> JsonToIEnumerable(string _json)
         {
             if (string.IsNullOrWhiteSpace(_json))
                 return null;
             IList<Hashtable> _list = new List<Hashtable>();
             object _r = JsonConvert.DeserializeObject(_json);
             if (_r is IEnumerable<JToken>)
             {
                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
                 {
                     Hashtable ht = new Hashtable();
                     foreach (KeyValuePair<string, JToken> _k in _i)
                     {
                         #region 循环属性
                         if (typeof(JValue) == _k.Value.GetType())
                         {
                             object _m = (_k.Value as JValue).Value;
                             if (_m != null)
                             {
                                 //判断是否符合2010-09-02T10:00:00的格式
                                 string s = _m.ToString();
                                  && s[] == ] == ] == ':')
                                 {
                                     ht[_k.Key] = Convert.ToDateTime(s);
                                 }
                                 else
                                 {
                                     ht[_k.Key] = s;
                                 }
                             }
                         }
                         #endregion
                     }
                     _list.Add(ht);
                 }
             }
             return _list;
         }

         /// <summary>
         /// 输入JSON,返回字典
         /// </summary>
         /// <param name="_json">json字符串</param>
         /// <returns>参数集合</returns>
         public static Dictionary<string, string> JsonToDictionary(string _json)
         {
             if (string.IsNullOrWhiteSpace(_json))
                 return null;
             Dictionary<string, string> _list = new Dictionary<string, string>();
             object _r = JsonConvert.DeserializeObject(_json);
             if (_r is IEnumerable<JToken>)
             {
                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
                 {
                     foreach (KeyValuePair<string, JToken> _k in _i)
                     {
                         #region 循环属性
                         if (typeof(JValue) == _k.Value.GetType())
                         {
                             object _m = (_k.Value as JValue).Value;
                             if (_m != null)
                             {
                                 //判断是否符合2010-09-02T10:00:00的格式
                                 string s = _m.ToString();
                                  && s[] == ] == ] == ':')
                                 {
                                     _list.Add(_k.Key, Convert.ToDateTime(s).ToString());
                                 }
                                 else
                                 {
                                     _list.Add(_k.Key, _k.Value.ToString());
                                 }
                             }
                         }
                         #endregion
                     }
                 }
             }
             return _list;
         }

         /// <summary>
         /// 输入JSON,返回字典
         /// </summary>
         /// <param name="_json">json字符串</param>
         /// <returns>参数集合</returns>
         public static IEnumerable<KeyValuePair<string, string>> JsonToIEDictionary(string _json)
         {
             if (string.IsNullOrWhiteSpace(_json))
                 return null;
             IList<KeyValuePair<string, string>> _list = new List<KeyValuePair<string, string>>();
             object _r = JsonConvert.DeserializeObject(_json);
             if (_r is IEnumerable<JToken>)
             {
                 foreach (IEnumerable<KeyValuePair<string, JToken>> _i in _r as IEnumerable<JToken>)
                 {
                     foreach (KeyValuePair<string, JToken> _k in _i)
                     {
                         #region 循环属性
                         if (typeof(JValue) == _k.Value.GetType())
                         {
                             object _m = (_k.Value as JValue).Value;
                             if (_m != null)
                             {
                                 //判断是否符合2010-09-02T10:00:00的格式
                                 string s = _m.ToString();
                                  && s[] == ] == ] == ':')
                                 {
                                     _list.Add(new KeyValuePair<string, string>(_k.Key, Convert.ToDateTime(s).ToString()));
                                 }
                                 else
                                 {
                                     _list.Add(new KeyValuePair<string, string>(_k.Key, _k.Value.ToString()));
                                 }
                             }
                         }
                         #endregion
                     }
                 }
             }
             return _list;
         }

         /// <summary>
         /// 实体对象转换为字符串
         /// </summary>
         /// <param name="o">实体对象</param>
         /// <returns>字符串</returns>
         public static string EntitiesToString(object o)
         {
             if (o == null || o.ToString() == "null") return null;

             if (o != null && (o.GetType() == typeof(String) || o.GetType() == typeof(string)))
             {
                 return o.ToString();
             }
             IsoDateTimeConverter dt = new IsoDateTimeConverter();
             dt.DateTimeFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss";
             return JsonConvert.SerializeObject(o, dt);
         }

         /// <summary>
         /// 类型转换
         /// </summary>
         /// <param name="value">数据</param>
         /// <param name="targetType">类型</param>
         /// <returns>数据类型</returns>
         private static Object ChangeType(object value, Type targetType)
         {
             Type convertType = targetType;
             if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
             {
                 NullableConverter nullableConverter = new NullableConverter(targetType);
                 convertType = nullableConverter.UnderlyingType;
             }
             return Convert.ChangeType(value, convertType);
         }

         /// <summary>
         /// 类型转换
         /// </summary>
         /// <typeparam name="T">目标类型</typeparam>
         /// <param name="convertibleValue">数据</param>
         /// <returns>返回类型</returns>
         public static T ConvertTo<T>(this IConvertible convertibleValue)
         {
             if (string.IsNullOrEmpty(convertibleValue.ToString()))
             {
                 return default(T);
             }
             if (!typeof(T).IsGenericType)
             {
                 return (T)Convert.ChangeType(convertibleValue, typeof(T));
             }
             else
             {
                 Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                 if (genericTypeDefinition == typeof(Nullable<>))
                 {
                     return (T)Convert.ChangeType(convertibleValue, Nullable.GetUnderlyingType(typeof(T)));
                 }
             }
             return default(T);
         }

         /// <summary>
         /// Hashtable转换为实体
         /// </summary>
         /// <typeparam name="T">实体类</typeparam>
         /// <param name="t">实体类对象</param>
         /// <param name="row">Hashtable数据源</param>
         public static void ConvertHashToEntity<T>(T t, Hashtable row) where T : class
         {
             PropertyInfo[] p = typeof(T).GetProperties();

             foreach (var item in p)
             {
                 item.SetValue(t, ChangeType(row[item.Name], item.PropertyType), null);
             }
         }
     }
 }

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. mysql 远程链接问题

    问题描述: 从一台linux远程连接另一台linux上的MySQL, 出现ERROR 2003 (HY000): Can't connect to MySQL server on 'xxx.xxx.x ...

  2. step5: 编写spider爬取

    改写parse函数 实现功能: 1.获取文章列表页中的文章url并交给scrapy下载后,交给解析函数进行具体字段的解析2.获取下一页的url并交给scrapy进行下载,下载完成后交给parse 提取 ...

  3. docker创建nginx镜像

    注意:此处不是用的dockerfile创建的镜像,只是用来搞一搞 首先你的系统里面要安装docker,这里就不重复介绍了,可以看之前的文章: 然后再搞一个基础镜像 docker pull regist ...

  4. postgres entityframework foreignkey

    public class Model { [Key, Column("id"), DatabaseGenerated(DatabaseGeneratedOption.Identit ...

  5. javaEE Design Patter(1)初步了解23种常用设计模式

    设计模式分为三大类: 创建型模式,共五种:工厂方法模式.抽象工厂模式.单例模式.建造者模式.原型模式. 结构型模式,共七种:适配器模式.装饰器模式.代理模式.外观模式.桥接模式.组合模式.享元模式. ...

  6. Win10自带Ubuntu子系统下Mysql安装踩坑记录

    linux系统为win10自带Ubuntu子系统 错误的安装过程 我按照一般的方法安装mysql,安装步骤如下 1.升级源 $ sudo apt-get update 2.安装mysql $ sudo ...

  7. svn的使用总结

    在网上看到了以前介绍非常全的svn的文章,拿来分享 原文网址  http://www.cnblogs.com/jx270/archive/2013/03/04/2943595.html 还有一篇更基础 ...

  8. Error running Tomcat8: Address localhost:1099 is already in use 错误解决

    摘要: 有时候运行web项目的时候会遇到 Error running Tomcat8: Address localhost:1099 is already in use 的错误,导致web项目无法运行 ...

  9. npm安装指定版本

    今天犯了一个低级错误,在npm安装依赖时,命令写成下了格式 npm i --save iview 2.0.0 要安装指定版本应该使用 npm i --save iview@2.0.0 谨记

  10. <Android 应用 之路> 百度地图API使用(3)

    前言 上一篇讲解并实践了百度地图基本显示,地图类型,实时交通图,热力图,地图控制和手势控制,今天看下在地图上添加view和覆盖物. 地图Logo不允许遮挡,可通过mBaiduMap.setPaddin ...