把一个json字符串转换成对应的c#类型

摘要:
放弃使用Newtonsoft,自己动手。=null){list.Add;}});returnlist;}privateList˂Dictionary˃GetMatchChips{List˂Dictionary˃dict=newList˂Dictionary˃();stringstrSource=source.Substring;//取得各个对象数据Regexregex=newRegex;MatchCollectionmatchs=regex.Matches;DictionarydictTemp;foreach{//TODOdictTemp=GetSpecifiedUnit;if(dictTemp!r.IsMatch){thrownewArgumentException("输入的数据含有非法字符!请检查后重新填写产品属性信息!
放弃使用Newtonsoft,自己动手。
using
System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Reflection; usingSystem.Text.RegularExpressions; namespaceConsoleApplication1 { classProgram { static void Main(string[] args) { string str = "[{AttributeValueCode:01,AttributeTypeKey:B72CD297-A47E-4081-BA7C-DFFF7BA726D4,AttributeValue:红色,SortOrder:1},{AttributeValueCode:02,AttributeTypeKey:B72CD297-A47E-4081-BA7C-DFFF7BA726D4,AttributeValue:金黄色,SortOrder:3}]"; List<Pro_ProductAttribute> list_ProductAttribute = (new Program()).GetFrontProductAttribueList<Pro_ProductAttribute>(str); Console.WriteLine(str); Console.Read(); } #region 类型转换 private List<T> GetFrontProductAttribueList<T>(stringsource) where T : new() { List<T> list = new List<T>(); //TODO: T entity; GetMatchChips(source).ForEach(delegate(Dictionary<string, string>item) { entity = SetObejctValue<T>(item); if (entity != null) { list.Add(entity); } }); returnlist; } private List<Dictionary<string, string>> GetMatchChips(stringsource) { List<Dictionary<string, string>> dict = new List<Dictionary<string, string>>(); string strSource = source.Substring(1, source.Length - 2); //取得各个对象数据 Regex regex = new Regex(@"({)([^}]+)(})"); MatchCollection matchs = regex.Matches(strSource, 0); Dictionary<string, string>dictTemp; foreach (Match m inmatchs) { //TODO dictTemp =GetSpecifiedUnit(m.ToString()); if (dictTemp != null) { dict.Add(dictTemp); } } returndict; } private Dictionary<string, string> GetSpecifiedUnit(stringsource) { Dictionary<string, string> dict = new Dictionary<string, string>(); Regex regex = new Regex(@"^({)([^}]+)(})"); if (!regex.IsMatch(source, 0)) { return null; } MatchCollection matchs = regex.Matches(source, 0); if (matchs.Count != 1) { return null; } string[] sourceChips = matchs[0].ToString().Substring(1,matchs[0].ToString().Length-2).ToString().Split(','); foreach (string str insourceChips) { Regex r = new Regex(@"([^:]+)"); if (!r.IsMatch(str, 0)) { throw new ArgumentException("输入的数据含有非法字符!请检查后重新填写产品属性信息!"); } MatchCollection mCollection = r.Matches(str, 0); //if (mCollection.Count != 1) { throw new ArgumentException("输入的数据含有非法字符!请检查后重新填写产品属性信息!"); } //string[] strDictUnit = mCollection[0].ToString().Split(':'); //dict.Add(strDictUnit[0], strDictUnit[1]); dict.Add(mCollection[0].ToString(), mCollection[1].ToString()); } returndict; } structRetrievePropertyStruct { public stringName; publicType PropertyType; public objectValue; } private RetrievePropertyStruct RetrieveProperty(object obj, stringpropertyName) { RetrievePropertyStruct retrievedDestination; retrievedDestination.Name =propertyName; PropertyInfo propertyInfo =obj.GetType().GetProperty(propertyName); Type propertyType = null; object retrievedObject = null; if (propertyInfo != null) { propertyType =propertyInfo.PropertyType; retrievedObject = propertyInfo.GetValue(obj, null); } else{ FieldInfo fieldInfo =obj.GetType().GetField(propertyName); if (fieldInfo != null) { propertyType =fieldInfo.FieldType; retrievedObject =fieldInfo.GetValue(obj); } } retrievedDestination.PropertyType =propertyType; retrievedDestination.Value =retrievedObject; returnretrievedDestination; } private T SetObejctValue<T>(Dictionary<string, string>source) where T : new() { T setObject = newT(); PropertyInfo[] propertyInfos =setObject.GetType().GetProperties(); Type propertyType = null; foreach (PropertyInfo propertyInfo inpropertyInfos) { propertyType =propertyInfo.PropertyType; IEnumerator<string> enumerator =source.Keys.GetEnumerator(); while(enumerator.MoveNext()) { string current =enumerator.Current; if (current ==propertyInfo.Name) { //数据类型转换需要作进一步的统一化就可以通用了 switch(propertyInfo.Name) { case "SortOrder": propertyInfo.SetValue(setObject, Int32.Parse(source[current]), null); break; case "AttributeTypeKey": propertyInfo.SetValue(setObject, new System.Guid(source[current]), null); break; default: propertyInfo.SetValue(setObject, source[current], null); break; } } }//end while(enumerator.MoveNext()) } returnsetObject; } #endregion} public classPro_ProductAttribute { #region Private Properties private Guid? _productAttributeKey;//产品属性主键 private Guid? _attributeTypeKey;//属性类型主键 private string _attributeTypeCode;//属性类型编码 private string _attributeTypeName;//属性类型名称 private Guid? _productModelKey;//产品型号主键 private string _productModelCode;//产品型号编码 private string _productModelName;//产品型号名称 private Guid? _attributeValueKey;//属性值主键 private string _attributeValueCode;//属性值编码 private string _attributeValue;//属性值 private int? _sortOrder;//排序号 private int? _weight;//权重 private DateTime? _createTime;//创建时间 private int? _createUser;//创建用户 private DateTime? _updateTime;//最近修改时间 private int? _updateUser;//最近修改用户 private bool? _deleteFlag;//删除标志 private DateTime? _deleteTime;//删除时间 private int? _deleteUser;//删除操作用户 #endregion #region Public Properties /// <summary> ///产品属性主键. /// </summary> //[ColumnMappingName = "ProductAttributeKey")] public Guid?ProductAttributeKey { get{ return_productAttributeKey; } set{ object _oldvalue =_productAttributeKey; _productAttributeKey =value; } } /// <summary> ///属性类型主键. /// </summary> //[ColumnMappingName = "AttributeTypeKey")] public Guid?AttributeTypeKey { get{ return_attributeTypeKey; } set{ object _oldvalue =_attributeTypeKey; _attributeTypeKey =value; } } /// <summary> ///属性类型编码. /// </summary> //[ColumnMappingName = "AttributeTypeCode")] public stringAttributeTypeCode { get{ return_attributeTypeCode; } set{ object _oldvalue =_attributeTypeCode; _attributeTypeCode =value; } } /// <summary> ///属性类型名称. /// </summary> //[ColumnMappingName = "AttributeTypeName")] public stringAttributeTypeName { get{ return_attributeTypeName; } set{ object _oldvalue =_attributeTypeName; _attributeTypeName =value; } } /// <summary> ///产品型号主键. /// </summary> //[ColumnMappingName = "ProductModelKey")] public Guid?ProductModelKey { get{ return_productModelKey; } set{ object _oldvalue =_productModelKey; _productModelKey =value; } } /// <summary> ///产品型号编码. /// </summary> //[ColumnMappingName = "ProductModelCode")] public stringProductModelCode { get{ return_productModelCode; } set{ object _oldvalue =_productModelCode; _productModelCode =value; } } /// <summary> ///产品型号名称. /// </summary> //[ColumnMappingName = "ProductModelName")] public stringProductModelName { get{ return_productModelName; } set{ object _oldvalue =_productModelName; _productModelName =value; } } /// <summary> ///属性值主键. /// </summary> //[ColumnMappingName = "AttributeValueKey")] public Guid?AttributeValueKey { get{ return_attributeValueKey; } set{ object _oldvalue =_attributeValueKey; _attributeValueKey =value; } } /// <summary> ///属性值编码. /// </summary> //[ColumnMappingName = "AttributeValueCode")] public stringAttributeValueCode { get{ return_attributeValueCode; } set{ object _oldvalue =_attributeValueCode; _attributeValueCode =value; } } /// <summary> ///属性值. /// </summary> //[ColumnMappingName = "AttributeValue")] public stringAttributeValue { get{ return_attributeValue; } set{ object _oldvalue =_attributeValue; _attributeValue =value; } } /// <summary> ///排序号. /// </summary> //[ColumnMappingName = "SortOrder")] public int?SortOrder { get{ return_sortOrder; } set{ object _oldvalue =_sortOrder; _sortOrder =value; } } /// <summary> ///权重. /// </summary> //[ColumnMappingName = "Weight")] public int?Weight { get{ return_weight; } set{ object _oldvalue =_weight; _weight =value; } } /// <summary> ///创建时间. /// </summary> //[ColumnMappingName = "CreateTime")] public DateTime?CreateTime { get{ return_createTime; } set{ object _oldvalue =_createTime; _createTime =value; } } /// <summary> ///创建用户. /// </summary> //[ColumnMappingName = "CreateUser")] public int?CreateUser { get{ return_createUser; } set{ object _oldvalue =_createUser; _createUser =value; } } /// <summary> ///最近修改时间. /// </summary> //[ColumnMappingName = "UpdateTime")] public DateTime?UpdateTime { get{ return_updateTime; } set{ object _oldvalue =_updateTime; _updateTime =value; } } /// <summary> ///最近修改用户. /// </summary> //[ColumnMappingName = "UpdateUser")] public int?UpdateUser { get{ return_updateUser; } set{ object _oldvalue =_updateUser; _updateUser =value; } } /// <summary> ///删除标志. /// </summary> //[ColumnMappingName = "DeleteFlag")] public bool?DeleteFlag { get{ return_deleteFlag; } set{ object _oldvalue =_deleteFlag; _deleteFlag =value; } } /// <summary> ///删除时间. /// </summary> //[ColumnMappingName = "DeleteTime")] public DateTime?DeleteTime { get{ return_deleteTime; } set{ object _oldvalue =_deleteTime; _deleteTime =value; } } /// <summary> ///删除操作用户. /// </summary> //[ColumnMappingName = "DeleteUser")] public int?DeleteUser { get{ return_deleteUser; } set{ object _oldvalue =_deleteUser; _deleteUser =value; } } #endregion} }

免责声明:文章转载自《把一个json字符串转换成对应的c#类型》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇java调用asmx的webservicepython unittest控制用例的执行顺序下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

微信公众平台获取用户openid

首先需要一个域名,如花生壳域名,然后在微信公众平台配置,注意,正式环境下必须要备案好了的域名,测试环境下没有关系,先公众号功能设置:》接口权限中的网页授权获取用户基本信息》注册一个测试者账号,进行设置,也要修改网页授权获取用户基本信息 public ActionResult Index(string id, string code, string st...

WMI获取驱动版本

WMI获取驱动版本 // public string GetDriverVersion(string HardwareID) //找出驱动版本// { // string queryString = "SELECT HardwareID, DriverVersion FROM Win32_PnPSignedDriver"; // SelectQuery s...

c#截取两个指定字符串中间的字符串(转载)

转载来源:https://www.cnblogs.com/jolins/p/9714238.html  写法有很多,记录常用的两种: 1、正则表达式 1 public static string MidStrEx_New(string sourse, string startstr, string endstr) 2 {...

VS2012_MVC4入门例子、代码视图分离办法、需要注意的坑爹问题等_被坑后不断更新此贴,要转载的话,请使用链接,不要转载内容

因为此贴会不断更新,所以,要转载的话,请使用链接,不要转载内容。 --------------------------------------------- 题外话: 用C#做网站,目前主要有两种模式:Asp.net网站,基于WebForm,和Mvc4 (mvc3、其他自定义框架就不谈了)。也就是做 xx.aspx页面,并且工具栏有一堆现成的.net服务器...

java 基本理论知识点

http://www.cnblogs.com/hellokitty1/p/4491808.html 1、main方法是怎么写的        public static void main(String [] args){}//最习惯的      public static void main(String  args[]){}      static p...

一款不错的多选下拉列表利器—— Ext.ux.form.SuperBoxSelect

       在B/S系统中,下拉列表(select/dropdownlist/combobox)的应用随处可见,为了增强用户体验,开发人员也常常会做一些带联想功能的下拉列表,         特别是数据项比较多的时候,用户筛选起来就会很容易。         如果考虑多选的场景,我想以下的实现方式很多时候是能够满足要求的: 带复选框(checkbox)...