自定义实现Json字符串向C#对象转变的方法
这里使用Atrribute的方式实现了Json字符串向C#对象的转变。因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK.";而不是Json数组。这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Json字符串中的哪个key.
namespaceJsonMapper
{
[AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=false)]
publicclassJsonFieldAttribute:Attribute
{
privatestring_Name=string.Empty;
publicstringName
{
get{return_Name;}
set{_Name=value;}
}
}
}
接下来是这个转换工具中的核心代码,主要是分解并且分析Json字符串中key与value,并且通过反射获得对象中的各个对应属性并且赋值。
namespaceJsonMapper
{
publicclassJsonToInstance
{
publicTToInstance<T>(stringjson)whereT:new()
{
Dictionary<string,string>dic=newDictionary<string,string>();
string[]fields=json.Split(",");
for(inti=0;i<fields.Length;i++)
{
string[]keyvalue=fields[i].Split(":");
dic.Add(Filter(keyvalue[0]),Filter(keyvalue[1]));
}
PropertyInfo[]properties=typeof(T).GetProperties(BindingFlags.Public|BindingFlags.Instance);
Tentity=newT();
foreach(PropertyInfopropertyinproperties)
{
object[]propertyAttrs=property.GetCustomAttributes(false);
for(inti=0;i<propertyAttrs.Length;i++)
{
objectpropertyAttr=propertyAttrs[i];
if(propertyAttrisJsonFieldAttribute)
{
JsonFieldAttributejsonFieldAttribute=propertyAttrasJsonFieldAttribute;
foreach(KeyValuePair<string,string>itemindic)
{
if(item.Key==jsonFieldAttribute.Name)
{
Typet=property.PropertyType;
property.SetValue(entity,ToType(t,item.Value),null);
break;
}
}
}
}
}
returnentity;
}
privatestringFilter(stringstr)
{
if(!(str.StartsWith("\"")&&str.EndsWith("\"")))
{
returnstr;
}
else
{
returnstr.Substring(1,str.Length-2);
}
}
publicobjectToType(Typetype,stringvalue)
{
if(type==typeof(string))
{
returnvalue;
}
MethodInfoparseMethod=null;
foreach(MethodInfomiintype.GetMethods(BindingFlags.Static
|BindingFlags.Public))
{
if(mi.Name=="Parse"&&mi.GetParameters().Length==1)
{
parseMethod=mi;
break;
}
}
if(parseMethod==null)
{
thrownewArgumentException(string.Format(
"Type:{0}hasnotParsestaticmethod!",type));
}
returnparseMethod.Invoke(null,newobject[]{value});
}
}
}
最后这是用于测试的代码
publicclassMessage
{
//{"result":100,"response":"Whoareyou?!","id":13185569,"msg":"OK."}
[JsonField(Name="result")]
publicintResult{get;set;}
[JsonField(Name="response")]
publicstringResponse{get;set;}
[JsonField(Name="id")]
publicintId{get;set;}
[JsonField(Name="msg")]
publicstringMsg{get;set;}
}
classProgram
{
staticvoidMain(string[]args)
{
JsonToInstanceutil=newJsonToInstance();
stringjson="\"response\":\"我是阿猫酱的小黄鸡\",\"id\":21231513,\"result\":100,\"msg\":\"OK.\"";
Messagem=util.ToInstance<Message>(json);
}
}
相关文章