自定义实现json字符串向c#对象转变的方法

自定义实现json字符串向c#对象转变的方法

ID:14043362

大小:20.00 KB

页数:3页

时间:2018-07-25

自定义实现json字符串向c#对象转变的方法_第1页
自定义实现json字符串向c#对象转变的方法_第2页
自定义实现json字符串向c#对象转变的方法_第3页
资源描述:

《自定义实现json字符串向c#对象转变的方法》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库

1、计算机交流平台:计算机故障_计算机论坛www.it168bbs.comwy自定义实现Json字符串向C#对象转变的方法这里使用Atrribute的方式实现了Json字符串向C#对象的转变。因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK.";而不是Json数组。这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Json字符串中的哪个key.[csharp]namespaceJsonMapper{[A

2、ttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=false)]publicclassJsonFieldAttribute:Attribute{privatestring_Name=string.Empty;publicstringName{get{return_Name;}set{_Name=value;}}}}接下来是这个转换工具中的核心代码,主要是分解并且分析Json字符串中key与value,并且通过反射获得对象中的各个对应属性并且赋值。[csharp]namespaceJsonMapp

3、er{publicclassJsonToInstance{publicTToInstance(stringjson)whereT:new(){Dictionarydic=newDictionary();string[]fields=json.Split(',');for(inti=0;i

4、fo[]properties=typeof(T).GetProperties(BindingFlags.Public

5、BindingFlags.Instance);Tentity=newT();foreach(PropertyInfopropertyinproperties){object[]propertyAttrs=property.GetCustomAttributes(false);for(inti=0;i

6、it168bbs.comwyif(propertyAttrisJsonFieldAttribute){JsonFieldAttributejsonFieldAttribute=propertyAttrasJsonFieldAttribute;foreach(KeyValuePairitemindic){if(item.Key==jsonFieldAttribute.Name){Typet=property.PropertyType;property.SetValue(entity,ToType(t,item.Value),null);break;}}}}

7、}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(Bin

8、dingFlags.Static

9、BindingFlags.Public)){if(mi.Name=="Parse"&&mi.GetParameters().Length==1){parseMethod=mi;break;}}计算机交流平台:计算机故障_计算机论坛www.it168bbs.comwyif(parseMethod==null){thrownewArgumentException(string.Format("Type:{0}hasnotPar

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。