我們知道在NET中我們有多種對象序列化的方式,如XML方式序列化、Binary序列化,其中XML序列化是一種比較通用的在各語言之間傳遞數據的方式。除了這兩種序列化方式之外,在NET中還可以使用JSON序列化。
JSON(JavaScript Object Notation)是一種輕量級輕量級的數據交換格式,並且它獨立於編程語言,與XML序列化相比,JSON序列化後產生的數據一般要比XML序列化後數據體積小,所以在Facebook等知名網站中都采用了JSON作為數據交換方式。在NET中有三種常用的JSON序列化的類,分別是 SystemWebScriptSerializationJavaScriptSerializer類、SystemRuntimeSerializationJsonDataContractJsonSerializer類和NewtonsoftJsonJsonConvert類。
為了便於下面的演示,下面提供一個類的代碼:
復制代碼 代碼如下:
[DataContract]
publicclass User
{
///<summary>
/// 編號
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用戶名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 創建時間
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相關URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
//[ScriptIgnore]//使用JavaScriptSerializer序列化時不序列化此字段
//[IgnoreDataMember]//使用DataContractJsonSerializer序列化時不序列化此字段
//[JsonIgnore]//使用JsonConvert序列化時不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 權利級別
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 權利級別
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
使用SystemWebScriptSerializationJavaScriptSerializer類
SystemWebScriptSerializationJavaScriptSerializer類是NET類庫中自帶的一種JSON序列化實現,在NET Framework5及以後版本中可以使用這個類,這個類位於SystemWebExtensionsdll中,使用這個類是必須添加對這個dll的引用。
下面的代碼是使用JavaScriptSerializer進行序列化和反序列化的例子:
復制代碼 代碼如下:
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer類在SystemWebExtensionsdll中,注意添加這個引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化後的結果:{0},長度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化後的結果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
說明:如果不想序列化某個字段,可以在字段前面加[JsonIgnore]標記。
使用SystemRuntimeSerializationJsonDataContractJsonSerializer類
SystemRuntimeSerializationJsonDataContractJsonSerializer類位於SystemServiceModelWebdll中,使用這個類時除了需要添加對SystemServiceModelWebdll的引用之外,還需要添加SystemRuntimeSerializationdll的引用,注意這個類也是在NET Framework5及以後版本中可以使用。
下面是使用DataContractJsonSerializer類的例子:
復制代碼 代碼如下:
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer類在SystemServiceModelWebdll中,注意添加這個引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化後的結果:{0},長度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化後的結果:UserId: {0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
注意:要使用DataContractJsonSerializer類進行序列化和反序列化,必須給類加上[DataContract]屬性,對要序列化的字段加上[DataMember]屬性,如果不想序列化某個字段或者屬性,可以加上[IgnoreDataMember]屬性。
使用NewtonsoftJsonJsonConvert類
NewtonsoftJsonJsonConvert類是非微軟提供的一個JSON序列化和反序列的開源免費的類庫(下載網址是:http://wwwcodeplexcom/json/),它提供了更靈活的序列化和反序列化控制,並且如果你的開發環境使用的是NET Framework5及以後版本的話,你就可以使用Linq to JSON,這樣一來面對一大段的數據不必一一解析,你可以使用Linq to JSON解析出你關心的那部分即可,非常方便。
下面是使用NewtonsoftJsonJsonConvert類的例子:
復制代碼 代碼如下:
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個dll並添加這個引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化後的結果:{0},長度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化後的結果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid JsonConvertLinqDemo()
{
User user =new User { UserId =1, UserName ="周公", CreateDate = DateTimeNowAddYears(-8), Birthday = DateTimeNowAddYears(-32), Priority = PriorityLowest, Salary =500, Urls =new List<string> { "http://zhoufoxcnblog51ctocom", "http://www.jb51.net" } };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個dll並添加這個引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化後的結果:{0},長度:{1}", result, resultLength);
//使用Linq to JSON
JObject jobject = JObjectParse(result);
JToken token = jobject["Urls"];
List<string> urlList =new List<string>();
foreach (JToken t in token)
{
urlListAdd(tToString());
}
ConsoleWrite("使用Linq to JSON反序列化後的結果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
注意:如果有不需要序列化的字段,可以給該字段添加[JsonIgnore]標記。在Newtonsoft這個類庫中對於日期的序列化有多種方式,可以類的DataTime成員添加上對應的標記,這樣在進行序列化和反序列化時就會按照指定的方式進行,在本例中User類的CreateDate屬性添加的屬性是[JsonConverter(typeof(IsoDateTimeConverter))],而Birthday屬性添加的屬性是[JsonConverter(typeof(JavaScriptDateTimeConverter))],從序列化的結果可以看出來它們最終的表現形式並不一樣。
本文中所有的示例代碼如下:
復制代碼 代碼如下:
using System;
using SystemCollectionsGeneric;
using SystemLinq;
using SystemText;
using SystemWebScriptSerialization;
using SystemRuntimeSerializationJson;
using SystemIO;
using SystemRuntimeSerialization;
using NewtonsoftJson;
using NewtonsoftJsonLinq;
using NewtonsoftJsonConverters;
namespace JSONDemo
{
class Program
{
staticvoid Main(string[] args)
{
JavaScriptSerializerDemo();
DataContractJsonSerializerDemo();
JsonConvertDemo();
JsonConvertLinqDemo();
ConsoleReadLine();
}
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer類在SystemWebExtensionsdll中,注意添加這個引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化後的結果:{0},長度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化後的結果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer類在SystemServiceModelWebdll中,注意添加這個引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化後的結果:{0},長度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化後的結果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個dll並添加這個引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化後的結果:{0},長度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化後的結果:UserId:{0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
publicstaticvoid JsonConvertLinqDemo()
{
User user =new User { UserId =1, UserName ="周公", CreateDate = DateTimeNowAddYears(-8), Birthday = DateTimeNowAddYears(-32), Priority = PriorityLowest, Salary =500, Urls =new List<string> { "http://zhoufoxcnblog51ctocom", "http://www.jb51.net" } };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個dll並添加這個引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化後的結果:{0},長度:{1}", result, resultLength);
//使用Linq to JSON
JObject jobject = JObjectParse(result);
JToken token = jobject["Urls"];
List<string> urlList =new List<string>();
foreach (JToken t in token)
{
urlListAdd(tToString());
}
ConsoleWrite("使用Linq to JSON反序列化後的結果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
}
[DataContract]
publicclass User
{
///<summary>
/// 編號
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用戶名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 創建時間
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相關URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
[ScriptIgnore]//使用JavaScriptSerializer序列化時不序列化此字段
[IgnoreDataMember]//使用DataContractJsonSerializer序列化時不序列化此字段
[JsonIgnore]//使用JsonConvert序列化時不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 權利級別
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 權利級別
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
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://office.jb51.net","http://www.jb51.net/web"],"Priority":1},長度:198
8.使用Linq to JSON反序列化後的結果:["http://office.jb51.net",http://www.jb51.net/web]
總結:通過上面的例子大家可以看出Newtonsoft類庫提供的JSON序列化和反序列的方式更加靈活,在實際開發中周公也一直使用Newtonsoft作為JSON序列化和反序列化的不二選擇。