jsonDLL 使用方法

我们知道在.NET中我们有多种对象序列化的方式,如XML方式序列化、Binary序列化,其中XML序列化是一种比较通用的在各语言之间传递数据的方式。除了这两种序列化方式之外,在.NET中还可以使用JSON序列化。 JSON(JavaScript Object Notation)是一种轻量级轻量级的数据交换格式,并且它独立于编程语言,与XML序列化相比,JSON序列化后产生的数据一般要比XML序列化后数据体积小,所以在Facebook等知名网站中都采用了JSON作为数据交换方式。在.NET中有三种常用的JSON序列化的类,分别是System.Web.Script.Serialization.JavaScriptSerializer类、System.Runtime.Serialization.Json.DataContractJsonSerializer类和Newtonsoft.Json.JsonConvert类。 为了便于下面的演示,下面提供一个类的代码:

 
  1. [DataContract] 
  2. publicclass User 
  3.     /// <summary> 
  4.     /// 编号 
  5.     /// </summary> 
  6.     [DataMember] 
  7.     publicint UserId { get; set; } 
  8.     /// <summary> 
  9.     /// 用户名 
  10.     /// </summary> 
  11.     [DataMember] 
  12.     publicstring UserName { get; set; } 
  13.     /// <summary> 
  14.     /// 创建时间 
  15.     /// </summary> 
  16.     [DataMember] 
  17.     [JsonConverter(typeof(IsoDateTimeConverter))] 
  18.     public DateTime CreateDate { get; set; } 
  19.     /// <summary> 
  20.     /// 生日 
  21.     /// </summary> 
  22.     [DataMember] 
  23.     [JsonConverter(typeof(JavaScriptDateTimeConverter))] 
  24.     public DateTime Birthday { get; set; } 
  25.     /// <summary> 
  26.     /// 相关URL 
  27.     /// </summary> 
  28.     [DataMember] 
  29.     public List<string> Urls { get; set; } 
  30.     /// <summary> 
  31.     /// 薪水 
  32.     /// </summary> 
  33.     //[ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段 
  34.     //[IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段 
  35.     //[JsonIgnore]//使用JsonConvert序列化时不序列化此字段 
  36.     publicint Salary { get; set; } 
  37.     /// <summary> 
  38.     /// 权利级别 
  39.     /// </summary> 
  40.     [DataMember] 
  41.     public Priority Priority { get; set; } 
  42.  
  43.     public User() 
  44.     { 
  45.         Urls = new List<string>(); 
  46.     } 
  47. /// <summary> 
  48. /// 权利级别 
  49. /// </summary> 
  50. publicenum Priority:byte 
  51.     Lowest=0x1, 
  52.     BelowNormal=0x2, 
  53.     Normal=0x4, 
  54.     AboveNormal=0x8, 
  55.     Highest=0x16 

 

使用System.Web.Script.Serialization.JavaScriptSerializer类System.Web.Script.Serialization.JavaScriptSerializer类是.NET类库中自带的一种JSON序列化实现,在.NET Framework3.5及以后版本中可以使用这个类,这个类位于System.Web.Extensions.dll中,使用这个类是必须添加对这个dll的引用。 下面的代码是使用JavaScriptSerializer进行序列化和反序列化的例子:

 
  1. publicstaticvoid JavaScriptSerializerDemo() 
  2.     User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30),Birthday=DateTime.Now.AddYears(-50), Priority = Priority.Highest, Salary = 500000 }; 
  3.     //JavaScriptSerializer类在System.Web.Extensions.dll中,注意添加这个引用 
  4.     JavaScriptSerializer serializer = new JavaScriptSerializer(); 
  5.     //JSON序列化 
  6.     string result=serializer.Serialize(user); 
  7.     Console.WriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, result.Length); 
  8.     //JSON反序列化 
  9.     user = serializer.Deserialize<User>(result); 
  10.     Console.WriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); 
  11.  

说明:如果不想序列化某个字段,可以在字段前面加[JsonIgnore]标记。

 

使用System.Runtime.Serialization.Json.DataContractJsonSerializer类 System.Runtime.Serialization.Json.DataContractJsonSerializer类位于System.ServiceModel.Web.dll中,使用这个类时除了需要添加对System.ServiceModel.Web.dll的引用之外,还需要添加System.Runtime.Serialization.dll的引用,注意这个类也是在.NET Framework3.5及以后版本中可以使用。 下面是使用DataContractJsonSerializer类的例子:

 
  1. publicstaticvoid DataContractJsonSerializerDemo() 
  2.     User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.AboveNormal, Salary = 50000 }; 
  3.     string result = string.Empty; 
  4.     //DataContractJsonSerializer类在System.ServiceModel.Web.dll中,注意添加这个引用 
  5.     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(User)); 
  6.      
  7.     using (MemoryStream stream = new MemoryStream()) 
  8.     { 
  9.         //JSON序列化 
  10.         serializer.WriteObject(stream, user); 
  11.         result = Encoding.UTF8.GetString(stream.ToArray()); 
  12.         Console.WriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, result.Length); 
  13.     } 
  14.  
  15.     //JSON反序列化 
  16.     byte[] buffer = Encoding.UTF8.GetBytes(result); 
  17.     using (MemoryStream stream = new MemoryStream(buffer)) 
  18.     { 
  19.         user = serializer.ReadObject(stream) as User; 
  20.         Console.WriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); 
  21.     } 

注意:要使用DataContractJsonSerializer类进行序列化和反序列化,必须给类加上[DataContract]属性,对要序列化的字段加上[DataMember]属性,如果不想序列化某个字段或者属性,可以加上[IgnoreDataMember]属性。

 

使用Newtonsoft.Json.JsonConvert类 Newtonsoft.Json.JsonConvert类是非微软提供的一个JSON序列化和反序列的开源免费的类库(下载网址是:http://www.codeplex.com/json/),它提供了更灵活的序列化和反序列化控制,并且如果你的开发环境使用的是.NET Framework3.5及以后版本的话,你就可以使用Linq to JSON,这样一来面对一大段的数据不必一一解析,你可以使用Linq to JSON解析出你关心的那部分即可,非常方便。 下面是使用Newtonsoft.Json.JsonConvert类的例子:

 
  1. publicstaticvoid JsonConvertDemo() 
  2.     User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.BelowNormal, Salary = 5000 }; 
  3.     //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 
  4.     //JSON序列化 
  5.     string result = JsonConvert.SerializeObject(user); 
  6.     Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); 
  7.     //JSON反序列化 
  8.     user = JsonConvert.DeserializeObject<User>(result); 
  9.     Console.WriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); 
  10.  
  11. publicstaticvoid JsonConvertLinqDemo() 
  12.     User user = new User { UserId = 1, UserName = "周公", CreateDate = DateTime.Now.AddYears(-8), Birthday = DateTime.Now.AddYears(-32), Priority = Priority.Lowest, Salary = 500, Urls = new List<string> { "http://zhoufoxcn.blog.51cto.com", "http://blog.csdn.net/zhoufoxcn" } }; 
  13.     //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 
  14.     //JSON序列化 
  15.     string result = JsonConvert.SerializeObject(user); 
  16.     Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); 
  17.     //使用Linq to JSON 
  18.     JObject jobject = JObject.Parse(result); 
  19.     JToken token = jobject["Urls"]; 
  20.     List<string> urlList = new List<string>(); 
  21.     foreach (JToken t in token) 
  22.     { 
  23.         urlList.Add(t.ToString()); 
  24.     } 
  25.     Console.Write("使用Linq to JSON反序列化后的结果:["); 
  26.     for (int i = 0; i < urlList.Count - 1;i++ ) 
  27.     { 
  28.         Console.Write(urlList[i] + ","); 
  29.     } 
  30.     Console.WriteLine(urlList[urlList.Count - 1] + "]"); 

注意:如果有不需要序列化的字段,可以给该字段添加[JsonIgnore]标记。在Newtonsoft这个类库中对于日期的序列化有多种方式,可以类的DataTime成员添加上对应的标记,这样在进行序列化和反序列化时就会按照指定的方式进行,在本例中User类的CreateDate属性添加的属性是[JsonConverter(typeof(IsoDateTimeConverter))],而Birthday属性添加的属性是[JsonConverter(typeof(JavaScriptDateTimeConverter))],从序列化的结果可以看出来它们最终的表现形式并不一样。 本文中所有的示例代码如下:

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. using System.Web.Script.Serialization; 
  6. using System.Runtime.Serialization.Json; 
  7. using System.IO; 
  8. using System.Runtime.Serialization; 
  9. using Newtonsoft.Json; 
  10. using Newtonsoft.Json.Linq; 
  11. using Newtonsoft.Json.Converters; 
  12.  
  13. namespace JSONDemo 
  14. class Program 
  15.     staticvoid Main(string[] args) 
  16.     { 
  17.         JavaScriptSerializerDemo(); 
  18.         DataContractJsonSerializerDemo(); 
  19.         JsonConvertDemo(); 
  20.         JsonConvertLinqDemo(); 
  21.         Console.ReadLine(); 
  22.     } 
  23.  
  24.     publicstaticvoid JavaScriptSerializerDemo() 
  25.     { 
  26.         User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30),Birthday=DateTime.Now.AddYears(-50), Priority = Priority.Highest, Salary = 500000 }; 
  27.         //JavaScriptSerializer类在System.Web.Extensions.dll中,注意添加这个引用 
  28.         JavaScriptSerializer serializer = new JavaScriptSerializer(); 
  29.         //JSON序列化 
  30.         string result=serializer.Serialize(user); 
  31.         Console.WriteLine("使用JavaScriptSerializer序列化后的结果:{0},长度:{1}", result, result.Length); 
  32.         //JSON反序列化 
  33.         user = serializer.Deserialize<User>(result); 
  34.         Console.WriteLine("使用JavaScriptSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); 
  35.  
  36.     } 
  37.  
  38.     publicstaticvoid DataContractJsonSerializerDemo() 
  39.     { 
  40.         User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.AboveNormal, Salary = 50000 }; 
  41.         string result = string.Empty; 
  42.         //DataContractJsonSerializer类在System.ServiceModel.Web.dll中,注意添加这个引用 
  43.         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(User)); 
  44.          
  45.         using (MemoryStream stream = new MemoryStream()) 
  46.         { 
  47.             //JSON序列化 
  48.             serializer.WriteObject(stream, user); 
  49.             result = Encoding.UTF8.GetString(stream.ToArray()); 
  50.             Console.WriteLine("使用DataContractJsonSerializer序列化后的结果:{0},长度:{1}", result, result.Length); 
  51.         } 
  52.  
  53.         //JSON反序列化 
  54.         byte[] buffer = Encoding.UTF8.GetBytes(result); 
  55.         using (MemoryStream stream = new MemoryStream(buffer)) 
  56.         { 
  57.             user = serializer.ReadObject(stream) as User; 
  58.             Console.WriteLine("使用DataContractJsonSerializer反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); 
  59.         } 
  60.     } 
  61.  
  62.     publicstaticvoid JsonConvertDemo() 
  63.     { 
  64.         User user = new User { UserId = 1, UserName = "李刚", CreateDate = DateTime.Now.AddYears(-30), Birthday = DateTime.Now.AddYears(-50), Priority = Priority.BelowNormal, Salary = 5000 }; 
  65.         //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 
  66.         //JSON序列化 
  67.         string result = JsonConvert.SerializeObject(user); 
  68.         Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); 
  69.         //JSON反序列化 
  70.         user = JsonConvert.DeserializeObject<User>(result); 
  71.         Console.WriteLine("使用JsonConvert反序列化后的结果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", user.UserId, user.UserName, user.CreateDate, user.Priority); 
  72.     } 
  73.  
  74.     publicstaticvoid JsonConvertLinqDemo() 
  75.     { 
  76.         User user = new User { UserId = 1, UserName = "周公", CreateDate = DateTime.Now.AddYears(-8), Birthday = DateTime.Now.AddYears(-32), Priority = Priority.Lowest, Salary = 500, Urls = new List<string> { "http://zhoufoxcn.blog.51cto.com", "http://blog.csdn.net/zhoufoxcn" } }; 
  77.         //JsonConvert类在Newtonsoft.Json.Net35.dll中,注意到http://www.codeplex.com/json/下载这个dll并添加这个引用 
  78.         //JSON序列化 
  79.         string result = JsonConvert.SerializeObject(user); 
  80.         Console.WriteLine("使用JsonConvert序列化后的结果:{0},长度:{1}", result, result.Length); 
  81.         //使用Linq to JSON 
  82.         JObject jobject = JObject.Parse(result); 
  83.         JToken token = jobject["Urls"]; 
  84.         List<string> urlList = new List<string>(); 
  85.         foreach (JToken t in token) 
  86.         { 
  87.             urlList.Add(t.ToString()); 
  88.         } 
  89.         Console.Write("使用Linq to JSON反序列化后的结果:["); 
  90.         for (int i = 0; i < urlList.Count - 1;i++ ) 
  91.         { 
  92.             Console.Write(urlList[i] + ","); 
  93.         } 
  94.         Console.WriteLine(urlList[urlList.Count - 1] + "]"); 
  95.     } 
  96.  
  97. [DataContract] 
  98. publicclass User 
  99.     /// <summary> 
  100.     /// 编号 
  101.     /// </summary> 
  102.     [DataMember] 
  103.     publicint UserId { get; set; } 
  104.     /// <summary> 
  105.     /// 用户名 
  106.     /// </summary> 
  107.     [DataMember] 
  108.     publicstring UserName { get; set; } 
  109.     /// <summary> 
  110.     /// 创建时间 
  111.     /// </summary> 
  112.     [DataMember] 
  113.     [JsonConverter(typeof(IsoDateTimeConverter))] 
  114.     public DateTime CreateDate { get; set; } 
  115.     /// <summary> 
  116.     /// 生日 
  117.     /// </summary> 
  118.     [DataMember] 
  119.     [JsonConverter(typeof(JavaScriptDateTimeConverter))] 
  120.     public DateTime Birthday { get; set; } 
  121.     /// <summary> 
  122.     /// 相关URL 
  123.     /// </summary> 
  124.     [DataMember] 
  125.     public List<string> Urls { get; set; } 
  126.     /// <summary> 
  127.     /// 薪水 
  128.     /// </summary> 
  129.     [ScriptIgnore]//使用JavaScriptSerializer序列化时不序列化此字段 
  130.     [IgnoreDataMember]//使用DataContractJsonSerializer序列化时不序列化此字段 
  131.     [JsonIgnore]//使用JsonConvert序列化时不序列化此字段 
  132.     publicint Salary { get; set; } 
  133.     /// <summary> 
  134.     /// 权利级别 
  135.     /// </summary> 
  136.     [DataMember] 
  137.     public Priority Priority { get; set; } 
  138.  
  139.     public User() 
  140.     { 
  141.         Urls = new List<string>(); 
  142.     } 
  143. /// <summary> 
  144. /// 权利级别 
  145. /// </summary> 
  146. publicenum Priority:byte 
  147.     Lowest=0x1, 
  148.     BelowNormal=0x2, 
  149.     Normal=0x4, 
  150.     AboveNormal=0x8, 
  151.     Highest=0x16 

程序的运行结果如下:

 

  1. 使用JavaScriptSerializer序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"//Date(353521211984)//","Birthday":"//Date(-277630788015)//","Urls":[],"Priority":22},长度:127 
  2. 使用JavaScriptSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-15 16:20:11,Priority:Highest 
  3. 使用DataContractJsonSerializer序列化后的结果:{"Birthday":"//Date(-277630787953+0800)//","CreateDate":"//Date(353521212046+0800)//","Priority":8,"Urls":[],"UserId":1,"UserName":"李刚"},长度:136 
  4. 使用DataContractJsonSerializer反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:AboveNormal 
  5. 使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"李刚","CreateDate":"1981-03-16T00:20:12.1875+08:00","Birthday":new Date(-277630787812),"Urls":[],"Priority":2},长度:132 
  6. 使用JsonConvert反序列化后的结果:UserId:1,UserName:李刚,CreateDate:1981-3-16 0:20:12,Priority:BelowNormal 
  7. 使用JsonConvert序列化后的结果:{"UserId":1,"UserName":"周公","CreateDate":"2003-03-16T00:20:12.40625+08:00","Birthday":new Date(290362812406),"Urls":["http://zhoufoxcn.blog.51cto.com","http://blog.csdn.net/zhoufoxcn"],"Priority":1},长度:198 
  8. 使用Linq to JSON反序列化后的结果:["http://zhoufoxcn.blog.51cto.com","http://blog.csdn.net/zhoufoxcn"] 

总结:通过上面的例子大家可以看出Newtonsoft类库提供的JSON序列化和反序列的方式更加灵活,在实际开发中周公也一直使用Newtonsoft作为JSON序列化和反序列化的不二选择。

 

周公

posted @ 2013-01-17 09:52  木子易  Views(984)  Comments(0Edit  收藏  举报