zoukankan      html  css  js  c++  java
  • 把URL传递参数转变成自定义实体方法

    先定义下要获取的实体:

      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 就是封装好的实体。 

  • 相关阅读:
    List数组细解
    iOS之缓存
    Java_String的操作
    weak的理解
    Swift_单利
    Java 抽象类和接口
    Java 继承中的问题
    java 成员变量与局部变量
    纪中第十九天
    cin快读
  • 原文地址:https://www.cnblogs.com/Karson001/p/4537189.html
Copyright © 2011-2022 走看看