自定义实现Json字符串向C#对象的转变

来源:互联网 发布:魅族手淘宝网的价格 编辑:程序博客网 时间:2024/05/01 09:58

这里使用Atrribute的方式实现了Json字符串向C#对象的转变。因为功能局限,此版本只是针对于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json数组。这里的Atrribute是作用在属性上,像NHibernate中的Atrribute一样,是在运行时通过反射来获取这个属性对应于Json字符串中的哪个key.

[csharp] view plaincopy
  1. namespace JsonMapper  
  2. {  
  3.     [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]  
  4.     public class JsonFieldAttribute : Attribute  
  5.     {  
  6.         private string _Name = string.Empty;  
  7.   
  8.         public string Name  
  9.         {  
  10.             get { return _Name; }  
  11.             set { _Name = value; }  
  12.         }  
  13.     }  
  14. }  
接下来是这个转换工具中的核心代码,主要是分解并且分析Json字符串中key与value, 并且通过反射获得对象中的各个对应属性并且赋值。
[csharp] view plaincopy
  1. namespace JsonMapper  
  2. {  
  3.     public class JsonToInstance  
  4.     {  
  5.         public T ToInstance<T>(string json) where T : new()  
  6.         {  
  7.             Dictionary<stringstring> dic = new Dictionary<stringstring>();  
  8.             string[] fields = json.Split(',');  
  9.             for (int i = 0; i < fields.Length; i++ )  
  10.             {  
  11.                 string[] keyvalue = fields[i].Split(':');  
  12.                 dic.Add(Filter(keyvalue[0]), Filter(keyvalue[1]));  
  13.             }  
  14.   
  15.             PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  16.   
  17.             T entity = new T();  
  18.             foreach (PropertyInfo property in properties)  
  19.             {  
  20.                 object[] propertyAttrs = property.GetCustomAttributes(false);  
  21.                 for (int i = 0; i < propertyAttrs.Length; i++)   
  22.                 {  
  23.                     object propertyAttr = propertyAttrs[i];  
  24.                     if (propertyAttr is JsonFieldAttribute)  
  25.                     {  
  26.                         JsonFieldAttribute jsonFieldAttribute = propertyAttr as JsonFieldAttribute;  
  27.                         foreach (KeyValuePair<string ,string> item in dic)  
  28.                         {  
  29.                             if (item.Key == jsonFieldAttribute.Name)  
  30.                             {  
  31.                                 Type t = property.PropertyType;  
  32.                                 property.SetValue(entity, ToType(t, item.Value), null);  
  33.                                 break;  
  34.                             }  
  35.                         }  
  36.                     }  
  37.                 }  
  38.             }  
  39.             return entity;  
  40.         }  
  41.   
  42.         private string Filter(string str)  
  43.         {  
  44.             if (!(str.StartsWith("\"") && str.EndsWith("\"")))  
  45.             {  
  46.                 return str;  
  47.             }  
  48.             else   
  49.             {  
  50.                 return str.Substring(1, str.Length - 2);  
  51.             }  
  52.         }  
  53.   
  54.         public object ToType(Type type, string value)  
  55.         {  
  56.             if (type == typeof(string))  
  57.             {  
  58.                 return value;  
  59.             }  
  60.   
  61.             MethodInfo parseMethod = null;  
  62.   
  63.             foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static   
  64.                 | BindingFlags.Public))  
  65.             {  
  66.                 if (mi.Name == "Parse" && mi.GetParameters().Length == 1)  
  67.                 {  
  68.                     parseMethod = mi;  
  69.                     break;  
  70.                 }  
  71.             }  
  72.   
  73.             if (parseMethod == null)  
  74.             {  
  75.                 throw new ArgumentException(string.Format(  
  76.                     "Type: {0} has not Parse static method!", type));  
  77.             }  
  78.   
  79.             return parseMethod.Invoke(nullnew object[] { value });  
  80.         }  
  81.     }  
  82. }  

最后这是用于测试的代码
[csharp] view plaincopy
  1. public class Message  
  2.     {  
  3.         //{ "result": 100, "response": "Who are you?!", "id": 13185569, "msg": "OK." }  
  4.   
  5.         [JsonField(Name = "result")]  
  6.         public int Result { getset; }  
  7.   
  8.         [JsonField(Name = "response")]  
  9.         public string Response { getset; }  
  10.   
  11.         [JsonField(Name = "id")]  
  12.         public int Id { getset; }  
  13.   
  14.         [JsonField(Name = "msg")]  
  15.         public string Msg { getset; }  
  16.     }  
[csharp] view plaincopy
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             JsonToInstance util = new JsonToInstance();  
  6.             string json = "\"response\":\"我是阿猫酱的小黄鸡\",\"id\":21231513,\"result\":100,\"msg\":\"OK.\"";  
  7.             Message m = util.ToInstance<Message>(json);  
  8.         }  
  9.     }  


0 0