先定义下要获取的实体:
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 就是封装好的实体。