自定义实现Json字符串向C#对象转变的方法
这里使用Atrribute的方式实现了Json字符串向C#对象的转变。因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json数组。这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Json字符串中的哪个key. 复制代码 代码如下: namespace JsonMapper { [AttributeUsage(AttributeTargets.Property,AllowMultiple = false,Inherited = false)] public class JsonFieldAttribute : Attribute { private string _Name = string.Empty; public string Name 接下来是这个转换工具中的核心代码,主要是分解并且分析Json字符串中key与value,并且通过反射获得对象中的各个对应属性并且赋值。 复制代码 代码如下: namespace JsonMapper { public class JsonToInstance { public T ToInstance<T>(string json) where T : new() { Dictionary<string,string> dic = new Dictionary<string,string>(); string[] fields = json.Split(','); for (int i = 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); T entity = new T(); private string Filter(string str) public object ToType(Type type,string value) MethodInfo parseMethod = null; foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static if (parseMethod == null) return parseMethod.Invoke(null,new object[] { value }); 最后这是用于测试的代码 复制代码 代码如下: public class Message { //{ "result": 100,"response": "Who are you?!","id": 13185569,"msg": "OK." } [JsonField(Name = "result")] [JsonField(Name = "response")] [JsonField(Name = "id")] [JsonField(Name = "msg")] 复制代码 代码如下: class Program { static void Main(string[] args) { JsonToInstance util = new JsonToInstance(); string json = ""response":"我是阿猫酱的小黄鸡","id":21231513,"result":100,"msg":"OK.""; Message m = util.ToInstance<Message>(json); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |