码迷,mamicode.com
首页 > Web开发 > 详细

把URL传递参数转变成自定义实体方法

时间:2015-05-29 00:23:25      阅读:641      评论:0      收藏:0      [点我收藏+]

标签:

先定义下要获取的实体:

  public class InputClass
    {
        public long Id { get; set; }
        public int Status { get; set; }

        public DateTime UdpateTime { get; set; }
    }

 

将url参数转换成对应字典类型

       private Dictionary<string, string> GetInputNameValues(string value)
        {
            var array = value.Split(new char[] { ‘&‘ }, StringSplitOptions.RemoveEmptyEntries);
            char[] split = new char[] { ‘=‘ };
            Dictionary<string, string> result = new Dictionary<string, string>(array.Length);
            foreach (var item in array)
            {
                var tempArr = item.Split(split, StringSplitOptions.RemoveEmptyEntries);
                if (tempArr.Length == 2)
                {
                    result.Add(tempArr[0], tempArr[1]);
                }
            }
            return result;
        }

 

将实体类转换字典方法:

        private Dictionary<string, System.Reflection.PropertyInfo> GetProperty(Type type)
        {
            var pro = type.GetProperties();
            var result = new Dictionary<string, PropertyInfo>(pro.Length);
            var jsonPropertyType = typeof(JsonPropertyAttribute);
            foreach (var item in pro)
            {
                var name = item.Name;
                var jsonpList = (JsonPropertyAttribute[])(item.GetCustomAttributes(jsonPropertyType, false));
                if (jsonpList.Length > 0)
                {
                    var jsonp = jsonpList.First();
                    JsonPropertyAttribute att = new JsonPropertyAttribute();
                    name = jsonp.PropertyName;
                }
                result.Add(name, item);
            }
            return result;
        }

 

主方法:

            var type = typeof(InputClass);
            string inputString = "Id=1111&Status=1&UdpateTime=2015-5-9";
            var model = new InputClass();
            var nameValues = GetInputNameValues(inputString);
            var propertyKeys = GetProperty(type);
            foreach (var item in propertyKeys)
            {
                string value;
                if (nameValues.TryGetValue(item.Key, out value))
                {
                    item.Value.SetValue(model, Convert.ChangeType(value, item.Value.PropertyType));
                }
            }
            return model;

 

返回的model 就是封装好的实体。 

 

把URL传递参数转变成自定义实体方法

标签:

原文地址:http://www.cnblogs.com/Karson001/p/4537189.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!