JsonHelp
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的更多相关文章
- 通用JSONHelp 的通用的封装
1. 最近项目已经上线了 ,闲暇了几天 想将JSON 的序列化 以及反序列化进行重新的封装一下本人定义为JSONHelp,虽然Microsoft 已经做的很好了.但是我想封装一套为自己开发的项目使用 ...
- C# 对象数据转换Json帮助类 JsonHelp
C# 对象数据转换Json帮助类 JsonHelp using System; using System.Data; using System.Configuration; using System. ...
- JSONHelp json解析成类,类解析成string
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization. ...
- Silverlight 使用DataContractJsonSerializer序列化与反序列化 Json
环境说明:Silverlight 5.1,.Net Framework 4.0 1.添加引用System.ServiceModel.Web.dll. 因为 System.Runtime.Seria ...
- .net 实体类与json转换(.net自带类库实现)更新
上一篇文章中写到在.net中实体类跟json格式的相互转换,今天在做具体转换时候,发现之前版本的jsonhelp对于日期类型的转换不全面.之前版本的jsonhelp中从实体类转换成json格式时候,将 ...
- .net 实体类与json转换(.net自带类库实现)
注意要点. 1.jsonhelp编写时候添加的引用.System.Runtime.Serialization.Json; 2.实体类需声明为public jsonhelp代码: using Syste ...
- C#中JSON序列化和反序列化
有一段时间没有到博客园写技术博客了,不过每天逛逛博客园中大牛的博客还是有的,学无止境…… 最近在写些调用他人接口的程序,用到了大量的JSON.XML序列化和反序列化,今天就来总结下json的序列化和反 ...
- 关于asp.net 开发的小技巧—让传值对象化
前端:前端 定义一个对象, 传值时实例此对象,序列化成json字符串 代码如下: 定义js对象: ///定义一个查询条件对象 var SearchCondition=function(){ this. ...
- 微信授权步骤与详解 -- c#篇
微信授权步骤与详解 -- c#篇 注:这里不涉及界面操作,只介绍代码操作. 1.基本原理如下: 从图上所知,第一步用户访问我们的网页,第二步我们后台跳转到微信授权页面,第三步用户点击授权,第四步微信重 ...
随机推荐
- php中array_walk() 和 array_map()两个函数区别
两个函数的共性和区别: 1.传入这两个函数的 $value,就是数组中的单一个元素. 2.array_walk() 仅返回true或者false,array_map() 返回处理后的数组: 3.要得到 ...
- Magento 2中文手册教程 - Magento 2 安装流程图
下图提供了安装Magento 2的安装流程概述: 设置你的服务器环境. 安装magento 2 必备软件, PHP, Apache, MySQL. 系统需求详细信息: 2.1.x 系统需求 获得mag ...
- ASP.Net Core MVC 网站在Windows服务器跑不起来
1.vs远程发布到服务器,浏览器访问,报错502 2.打开错误提示提供的网址参考 3.安装runtime,sdk,Hosting Bundle Installer,其他操作 .....发现并没有什么用 ...
- post方式发送接收文件
//文件post发送 var express = require('express');var router = express.Router();var request = require(&quo ...
- python监控linux内存并写入mongodb
(需要安装psutil 用来获取服务器资源,以及pymongo驱动)#pip install psutil #pip install pymongo #vim memory_monitory.py 文 ...
- Spring相关概念的理解理解
spring 框架的优点是一个轻量级比较简单易学的框架,实际使用中的有点优点有哪些呢!1.降低了组件之间的耦合性 ,实现了软件各层之间的解耦 2.可以使用容易提供的众多服务,如事务管理,消息服务等 3 ...
- GET和POST请求的区别如下
POST和GET都是向服务器提交数据,并且都会从服务器获取数据. 区别: 1.传送方式:get通过地址栏传输,post通过报文传输. 2.传送长度:get参数有长度限制(受限于url长度),而post ...
- linux设置静态获取ip
vsphere client 创建虚拟机后,默认是动态获取ip ,如果想要改为静态ip: 修改网卡eth0 (不一定每个人都是eth0,比如有的是ens160) vim /etc/sysconfig/ ...
- jQuery多次选中checkbox失效
在做项目的过程中,遇到一个问题.就是使用jquery的attr方法即 $("#aaa").attr('checked',true); $("#aaa").att ...
- 解决vue移动端适配问题
1,先看看网上关于移动端适配讲解 再聊移动端页面适配,rem和vw适配方案! 基础点:rem相对根节点字体的大小.所以不用px; 根字体:字体的大小px; px:你就当成cm(厘米)这样的东西吧: 基 ...