时间:2020-10-16 22:04:44 | 栏目:.NET代码 | 点击:次
这里使用Atrribute的方式实现了Json字符串向C#对象的转变。因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json数组。这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Json字符串中的哪个key.
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
T entity = new T();
foreach (PropertyInfo property in properties)
{
object[] propertyAttrs = property.GetCustomAttributes(false);
for (int i = 0; i < propertyAttrs.Length; i++)
{
object propertyAttr = propertyAttrs[i];
if (propertyAttr is JsonFieldAttribute)
{
JsonFieldAttribute jsonFieldAttribute = propertyAttr as JsonFieldAttribute;
foreach (KeyValuePair<string ,string> item in dic)
{
if (item.Key == jsonFieldAttribute.Name)
{
Type t = property.PropertyType;
property.SetValue(entity, ToType(t, item.Value), null);
break;
}
}
}
}
}
return entity;
}
private string Filter(string str)
{
if (!(str.StartsWith("\"") && str.EndsWith("\"")))
{
return str;
}
else
{
return str.Substring(1, str.Length - 2);
}
}
public object ToType(Type type, string value)
{
if (type == typeof(string))
{
return value;
}
MethodInfo parseMethod = null;
foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static
| BindingFlags.Public))
{
if (mi.Name == "Parse" && mi.GetParameters().Length == 1)
{
parseMethod = mi;
break;
}
}
if (parseMethod == null)
{
throw new ArgumentException(string.Format(
"Type: {0} has not Parse static method!", type));
}
return parseMethod.Invoke(null, new object[] { value });
}
}
}
最后这是用于测试的代码
[JsonField(Name = "result")]
public int Result { get; set; }
[JsonField(Name = "response")]
public string Response { get; set; }
[JsonField(Name = "id")]
public int Id { get; set; }
[JsonField(Name = "msg")]
public string Msg { get; set; }
}