C#对象转换工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization; namespace Com.AppCode.Helper
{
public class ObjectHelper
{
#region Invoking /// <summary>
/// test
/// </summary>
public void test()
{
var obj = new
{
id = ,
name = "张三",
sex = ,
age = };
//转换
var userModel = ConvertObject<user>(obj);
} /// <summary>
/// 用户
/// </summary>
public class user
{
/// <summary>
/// 编号
/// </summary>
public int id { set; get; } /// <summary>
/// 姓名
/// </summary>
public string name { set; get; } /// <summary>
/// 性别
/// </summary>
public int sex { set; get; } /// <summary>
/// 年龄
/// </summary>
public int age { set; get; } }
#endregion #region Method1 /// <summary>
/// 将object对象转换为实体对象
/// </summary>
/// <typeparam name="T">实体对象类名</typeparam>
/// <param name="asObject">object对象</param>
/// <returns></returns>
public T ConvertObject<T>(object asObject) where T : new()
{
//创建实体对象实例
var t = Activator.CreateInstance<T>();
if (asObject != null)
{
Type type = asObject.GetType();
//遍历实体对象属性
foreach (var info in typeof(T).GetProperties())
{
object obj = null;
//取得object对象中此属性的值
var val = type.GetProperty(info.Name)?.GetValue(asObject);
if (val != null)
{
//非泛型
if (!info.PropertyType.IsGenericType)
obj = Convert.ChangeType(val, info.PropertyType);
else//泛型Nullable<>
{
Type genericTypeDefinition = info.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
obj = Convert.ChangeType(val, Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
obj = Convert.ChangeType(val, info.PropertyType);
}
}
info.SetValue(t, obj, null);
}
}
}
return t;
} #endregion #region Method2 /// <summary>
/// 将object对象转换为实体对象
/// </summary>
/// <typeparam name="T">实体对象类名</typeparam>
/// <param name="asObject">object对象</param>
/// <returns></returns>
public static T ConvertObjectByJson<T>(object asObject) where T : new()
{
var serializer = new JavaScriptSerializer();
//将object对象转换为json字符
var json = serializer.Serialize(asObject);
//将json字符转换为实体对象
var t = serializer.Deserialize<T>(json);
return t;
}
#endregion #region Method3
/// <summary>
/// 将object尝试转为指定对象
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static T ConvertObjToModel<T>(object data) where T : new()
{
if (data == null) return new T();
// 定义集合
T result = new T(); // 获得此模型的类型
Type type = typeof(T);
string tempName = ""; // 获得此模型的公共属性
PropertyInfo[] propertys = result.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查object是否包含此列 // 判断此属性是否有Setter
if (!pi.CanWrite) continue; try
{
object value = GetPropertyValue(data, tempName);
if (value != DBNull.Value)
{
Type tempType = pi.PropertyType;
pi.SetValue(result, GetDataByType(value, tempType), null); }
}
catch
{ } } return result;
} /// <summary>
/// 获取一个类指定的属性值
/// </summary>
/// <param name="info">object对象</param>
/// <param name="field">属性名称</param>
/// <returns></returns>
public static object GetPropertyValue(object info, string field)
{
if (info == null) return null;
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
return property.First().GetValue(info, null);
} /// <summary>
/// 将数据转为制定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data1"></param>
/// <returns></returns>
public static object GetDataByType(object data1, Type itype, params object[] myparams)
{
object result = new object();
try
{
if (itype == typeof(decimal))
{
result = Convert.ToDecimal(data1);
if (myparams.Length > )
{
result = Convert.ToDecimal(Math.Round(Convert.ToDecimal(data1), Convert.ToInt32(myparams[])));
}
}
else if (itype == typeof(double))
{ if (myparams.Length > )
{
result = Convert.ToDouble(Math.Round(Convert.ToDouble(data1), Convert.ToInt32(myparams[])));
}
else
{
result = double.Parse(Convert.ToDecimal(data1).ToString("0.00"));
}
}
else if (itype == typeof(Int32))
{
result = Convert.ToInt32(data1);
}
else if (itype == typeof(DateTime))
{
result = Convert.ToDateTime(data1);
}
else if (itype == typeof(Guid))
{
result = new Guid(data1.ToString());
}
else if (itype == typeof(string))
{
result = data1.ToString();
}
}
catch
{
if (itype == typeof(decimal))
{
result = ;
}
else if (itype == typeof(double))
{
result = ;
}
else if (itype == typeof(Int32))
{
result = ;
}
else if (itype == typeof(DateTime))
{
result = null;
}
else if (itype == typeof(Guid))
{
result = Guid.Empty;
}
else if (itype == typeof(string))
{
result = "";
}
}
return result;
}
#endregion }
}
C#对象转换工具类的更多相关文章
- Json与javaBean之间的转换工具类
/** * Json与javaBean之间的转换工具类 * * {@code 现使用json-lib组件实现 * 需要 * json-lib-2.4-jdk15.jar * ...
- Json转换工具类(基于google的Gson和阿里的fastjson)
在项目之中我们经常会涉及到字符串和各种对象的转换,为此特地整理了一下常用的转换方法 一.基于com.google.code.gson封装的json转换工具类 1. 在pom.xml文件里面引入gson ...
- 时间日期转换工具类,获取当前时间YYYYMMDD24HHMISS、YYYYMMDDHHMISS
YYYYMMDD24HHMISS:24小时制时间(显示上只是比YYYYMMDDHHMISS中间多了一个24),例:2018102224112440 YYYYMMDDHHMISS:12小时制时间,例20 ...
- 对象转换工具 MapStruct 介绍
前言 在我们日常开发的分层结构的应用程序中,为了各层之间互相解耦,一般都会定义不同的对象用来在不同层之间传递数据,因此,就有了各种 XXXDTO.XXXVO.XXXBO 等基于数据库对象派生出来的对象 ...
- 日期转换工具类 CommUtil.java
package com.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.ut ...
- Android Bitmap与DrawAble与byte[]与InputStream之间的转换工具类【转】
package com.soai.imdemo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; ...
- java 二进制数字符串转换工具类
java 二进制数字符串转换工具类 将二进制转换成八进制 将二进制转换成十进制 将二进制转换成十六进制 将十进制转换成二进制 package com.iteye.injavawetrust.ad; i ...
- DensityUtil【尺寸转换工具类(px、dp互相转换)】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 用于项目中dp.px.sp之间的转换以及指定缩放值下的转换. 效果图 暂不需要 代码分析 常用的方法是px2dip.dip2px: ...
- 【Java】字节数组转换工具类
import org.apache.commons.lang.ArrayUtils; import java.nio.charset.Charset; /** * 字节数组转换工具类 */ publi ...
随机推荐
- Comet OJ - Contest #6 B.双倍快乐(二维最大上升子序列和)
双倍快乐 题目描述 Illyasviel:"你想要最长不下降子序列吗?" star-dust:"好啊!" Illyasviel:"老板,给我整两个最长 ...
- [RK3288] 外接USB设备出现丢数
CPU:RK3288 系统:Android 5.1 主板外接 USB 接口的外设,经常会出现丢数的现象,这种问题在很多 USB 接口的外设上都遇到过,例如:USB读卡器.USB扫描枪等 有一个共同点是 ...
- jquery判断一个标签是否包含另外一个标签
jquery判断一个标签是否包含另外一个标签 一.总结 一句话总结: jquery的find方法配合length属性:if($("#video_md_9_1").find(&quo ...
- PHP中定义常量的区别,define() 与 const
正文 在PHP5.3中,有两种方法可以定义常量: 使用const关键字 使用define()方法 const FOO = 'BAR'; define('FOO','BAR'); 这两种方式的根本区 ...
- Oralce JDBC jar包下载
下载地址:https://pan.baidu.com/s/1sU7gu4biigEAw-3Bu7yIOA 下载包中包括以下文件: ojdbc5.jarojdbc5dms.jarojdbc5dms_g. ...
- HADOOP回顾
1. hadoop 分为四大模块 common 其他组件的公共一来模块 HDFS 分布式模块提供高吞吐量的数据访问 mapreduce 分布式计算模块 yarn 作业调度和集群资源管理模块 2. 安 ...
- Json序列化指定输出字段 忽略属性
DataContract 服务契约定义了远程访问对象和可供调用的方法,数据契约则是服务端和客户端之间要传送的自定义数据类型. 一旦声明一个类型为DataContract,那么该类型就可以被序列化在服务 ...
- js求数组最大值方法
定义数组 var arr = [-1, 1, 101, -52, 10, 1001, 1001] 1.es6拓展运算符... Math.max(...arr) 2.es5 apply(与方法1原理相同 ...
- 亲历谷歌 Chrome 浏览器弹窗境外广告的解决方法(图) | 技术乐园
亲历谷歌 Chrome 浏览器弹窗境外广告的解决方法(图) | 技术乐园 转 https://www.hack520.com/338.html 谷歌的 Chrome 浏览器是我非常喜欢的一款的浏览器, ...
- Win10系统安装VMware-viclient-6.0无响应问题解决方法
背景:笔记本重做系统升级至Win10系统后,由于工作需要,得安装VMware-viclient-6.0软件进行远程连接. 问题:没有出现网上那种各种报错情况,只是在点击“安装”按钮的时候没弹出任何等待 ...