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

上传人:wm****3 文档编号:40948649 上传时间:2018-05-27 格式:DOC 页数:3 大小:20KB
返回 下载 相关 举报
自定义实现json字符串向c#对象转变的方法_第1页
第1页 / 共3页
自定义实现json字符串向c#对象转变的方法_第2页
第2页 / 共3页
自定义实现json字符串向c#对象转变的方法_第3页
第3页 / 共3页
亲,该文档总共3页,全部预览完了,如果喜欢就下载吧!
资源描述

《自定义实现json字符串向c#对象转变的方法》由会员分享,可在线阅读,更多相关《自定义实现json字符串向c#对象转变的方法(3页珍藏版)》请在金锄头文库上搜索。

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

2、amespace JsonMapper AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false) public class JsonFieldAttribute : Attribute private string _Name = string.Empty; public string Name get return _Name; set _Name = value; 接下来是这个转换工具中的核心代码,主要是分解并且分析 Json 字符串中 key 与 value, 并 且通过反射获得

3、对象中的各个对应属性并且赋值。 csharp namespace JsonMapper public class JsonToInstance public T ToInstance(string json) where T : new() Dictionary dic = new Dictionary(); string fields = json.Split(,); for (int i = 0; i item in dic) if (item.Key = jsonFieldAttribute.Name) Type t = property.PropertyType; property.S

4、etValue(entity, ToType(t, item.Value), null); break; return entity; private string Filter(string str) if (!(str.StartsWith(“) 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 (Me

5、thodInfo mi in type.GetMethods(BindingFlags.Static | BindingFlags.Public) if (mi.Name = “Parse“ break; 计算机交流平台:计算机故障_计算机论坛 wyif (parseMethod = null) throw new ArgumentException(string.Format( “Type: 0 has not Parse static method!“, type); return parseMethod.Invoke(null, new object value ); 最后这是用于测试

6、的代码 csharp public class Message / “result“: 100, “response“: “Who are you?!“, “id“: 13185569, “msg“: “OK.“ 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; csharp class Program static void Main(string args) JsonToInstance util = new JsonToInstance(); string json = “response“:“我是阿猫酱的小黄鸡 “,“id“:21231513,“result“:100,“msg“:“OK.“; Message m = util.ToInstance(json);

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 生活休闲 > 社会民生

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号