本篇內(nèi)容主要講解“在.NET如何使用JSON作為數(shù)據(jù)交換格式”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“在.NET如何使用JSON作為數(shù)據(jù)交換格式”吧!
員工經(jīng)過(guò)長(zhǎng)期磨合與沉淀,具備了協(xié)作精神,得以通過(guò)團(tuán)隊(duì)的力量開發(fā)出優(yōu)質(zhì)的產(chǎn)品。成都創(chuàng)新互聯(lián)堅(jiān)持“專注、創(chuàng)新、易用”的產(chǎn)品理念,因?yàn)椤皩W⑺詫I(yè)、創(chuàng)新互聯(lián)網(wǎng)站所以易用所以簡(jiǎn)單”。公司專注于為企業(yè)提供成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、微信公眾號(hào)開發(fā)、電商網(wǎng)站開發(fā),成都小程序開發(fā),軟件按需網(wǎng)站設(shè)計(jì)等一站式互聯(lián)網(wǎng)企業(yè)服務(wù)。我們知道在NET中我們有多種對(duì)象序列化的方式,如XML方式序列化、Binary序列化,其中XML序列化是一種比較通用的在各語(yǔ)言之間傳遞數(shù)據(jù)的方式。除了這兩種序列化方式之外,在NET中還可以使用JSON序列化。
JSON(JavaScript Object Notation)是一種輕量級(jí)輕量級(jí)的數(shù)據(jù)交換格式,并且它獨(dú)立于編程語(yǔ)言,與XML序列化相比,JSON序列化后產(chǎn)生的數(shù)據(jù)一般要比XML序列化后數(shù)據(jù)體積小,所以在Facebook等知名網(wǎng)站中都采用了JSON作為數(shù)據(jù)交換方式。在NET中有三種常用的JSON序列化的類,分別是 SystemWebScriptSerializationJavaScriptSerializer類、SystemRuntimeSerializationJsonDataContractJsonSerializer類和NewtonsoftJsonJsonConvert類。
為了便于下面的演示,下面提供一個(gè)類的代碼:
復(fù)制代碼 代碼如下:
[DataContract]
publicclass User
{
///<summary>
/// 編號(hào)
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用戶名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 創(chuàng)建時(shí)間
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相關(guān)URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
//[ScriptIgnore]//使用JavaScriptSerializer序列化時(shí)不序列化此字段
//[IgnoreDataMember]//使用DataContractJsonSerializer序列化時(shí)不序列化此字段
//[JsonIgnore]//使用JsonConvert序列化時(shí)不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 權(quán)利級(jí)別
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 權(quán)利級(jí)別
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
使用SystemWebScriptSerializationJavaScriptSerializer類
SystemWebScriptSerializationJavaScriptSerializer類是NET類庫(kù)中自帶的一種JSON序列化實(shí)現(xiàn),在NET Framework5及以后版本中可以使用這個(gè)類,這個(gè)類位于SystemWebExtensionsdll中,使用這個(gè)類是必須添加對(duì)這個(gè)dll的引用。
下面的代碼是使用JavaScriptSerializer進(jìn)行序列化和反序列化的例子:
復(fù)制代碼 代碼如下:
publicstaticvoid JavaScriptSerializerDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30),Birthday=DateTimeNowAddYears(-50), Priority = PriorityHighest, Salary =500000 };
//JavaScriptSerializer類在SystemWebExtensionsdll中,注意添加這個(gè)引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化后的結(jié)果:{0},長(zhǎng)度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化后的結(jié)果:UserId:{0},UserName: {1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
說(shuō)明:如果不想序列化某個(gè)字段,可以在字段前面加[JsonIgnore]標(biāo)記。
使用SystemRuntimeSerializationJsonDataContractJsonSerializer類
SystemRuntimeSerializationJsonDataContractJsonSerializer類位于SystemServiceModelWebdll中,使用這個(gè)類時(shí)除了需要添加對(duì)SystemServiceModelWebdll的引用之外,還需要添加SystemRuntimeSerializationdll的引用,注意這個(gè)類也是在NET Framework5及以后版本中可以使用。
下面是使用DataContractJsonSerializer類的例子:
復(fù)制代碼 代碼如下:
publicstaticvoid DataContractJsonSerializerDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityAboveNormal, Salary =50000 };
string result =stringEmpty;
//DataContractJsonSerializer類在SystemServiceModelWebdll中,注意添加這個(gè)引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化后的結(jié)果:{0},長(zhǎng)度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化后的結(jié)果:UserId: {0},UserName:{1},CreateDate:{2},Priority:{3}", userUserId, userUserName, userCreateDate, userPriority);
}
}
注意:要使用DataContractJsonSerializer類進(jìn)行序列化和反序列化,必須給類加上[DataContract]屬性,對(duì)要序列化的字段加上[DataMember]屬性,如果不想序列化某個(gè)字段或者屬性,可以加上[IgnoreDataMember]屬性。
使用NewtonsoftJsonJsonConvert類
NewtonsoftJsonJsonConvert類是非微軟提供的一個(gè)JSON序列化和反序列的開源免費(fèi)的類庫(kù)(下載網(wǎng)址是:http://wwwcodeplexcom/json/),它提供了更靈活的序列化和反序列化控制,并且如果你的開發(fā)環(huán)境使用的是NET Framework5及以后版本的話,你就可以使用Linq to JSON,這樣一來(lái)面對(duì)一大段的數(shù)據(jù)不必一一解析,你可以使用Linq to JSON解析出你關(guān)心的那部分即可,非常方便。
下面是使用NewtonsoftJsonJsonConvert類的例子:
復(fù)制代碼 代碼如下:
publicstaticvoid JsonConvertDemo()
{
User user =new User { UserId =1, UserName ="李剛", CreateDate = DateTimeNowAddYears(-30), Birthday = DateTimeNowAddYears(-50), Priority = PriorityBelowNormal, Salary =5000 };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個(gè)dll并添加這個(gè)引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的結(jié)果:{0},長(zhǎng)度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化后的結(jié)果: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", "https://www.jb51.net" } };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個(gè)dll并添加這個(gè)引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的結(jié)果:{0},長(zhǎng)度:{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反序列化后的結(jié)果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
注意:如果有不需要序列化的字段,可以給該字段添加[JsonIgnore]標(biāo)記。在Newtonsoft這個(gè)類庫(kù)中對(duì)于日期的序列化有多種方式,可以類的DataTime成員添加上對(duì)應(yīng)的標(biāo)記,這樣在進(jìn)行序列化和反序列化時(shí)就會(huì)按照指定的方式進(jìn)行,在本例中User類的CreateDate屬性添加的屬性是[JsonConverter(typeof(IsoDateTimeConverter))],而Birthday屬性添加的屬性是[JsonConverter(typeof(JavaScriptDateTimeConverter))],從序列化的結(jié)果可以看出來(lái)它們最終的表現(xiàn)形式并不一樣。
本文中所有的示例代碼如下:
復(fù)制代碼 代碼如下:
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中,注意添加這個(gè)引用
JavaScriptSerializer serializer =new JavaScriptSerializer();
//JSON序列化
string result=serializerSerialize(user);
ConsoleWriteLine("使用JavaScriptSerializer序列化后的結(jié)果:{0},長(zhǎng)度:{1}", result, resultLength);
//JSON反序列化
user = serializerDeserialize<User>(result);
ConsoleWriteLine("使用JavaScriptSerializer反序列化后的結(jié)果: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中,注意添加這個(gè)引用
DataContractJsonSerializer serializer =new DataContractJsonSerializer(typeof(User));
using (MemoryStream stream =new MemoryStream())
{
//JSON序列化
serializerWriteObject(stream, user);
result = EncodingUTFGetString(streamToArray());
ConsoleWriteLine("使用DataContractJsonSerializer序列化后的結(jié)果:{0},長(zhǎng)度:{1}", result, resultLength);
}
//JSON反序列化
byte[] buffer = EncodingUTFGetBytes(result);
using (MemoryStream stream =new MemoryStream(buffer))
{
user = serializerReadObject(stream) as User;
ConsoleWriteLine("使用DataContractJsonSerializer反序列化后的結(jié)果: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/下載這個(gè)dll并添加這個(gè)引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的結(jié)果:{0},長(zhǎng)度:{1}", result, resultLength);
//JSON反序列化
user = JsonConvertDeserializeObject<User>(result);
ConsoleWriteLine("使用JsonConvert反序列化后的結(jié)果: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", "https://www.jb51.net" } };
//JsonConvert類在NewtonsoftJsonNetdll中,注意到http://wwwcodeplexcom/json/下載這個(gè)dll并添加這個(gè)引用
//JSON序列化
string result = JsonConvertSerializeObject(user);
ConsoleWriteLine("使用JsonConvert序列化后的結(jié)果:{0},長(zhǎng)度:{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反序列化后的結(jié)果:[");
for (int i =0; i < urlListCount -1;i++ )
{
ConsoleWrite(urlList[i] +",");
}
ConsoleWriteLine(urlList[urlListCount -1] +"]");
}
}
[DataContract]
publicclass User
{
///<summary>
/// 編號(hào)
///</summary>
[DataMember]
publicint UserId { get; set; }
///<summary>
/// 用戶名
///</summary>
[DataMember]
publicstring UserName { get; set; }
///<summary>
/// 創(chuàng)建時(shí)間
///</summary>
[DataMember]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime CreateDate { get; set; }
///<summary>
/// 生日
///</summary>
[DataMember]
[JsonConverter(typeof(JavaScriptDateTimeConverter))]
public DateTime Birthday { get; set; }
///<summary>
/// 相關(guān)URL
///</summary>
[DataMember]
public List<string> Urls { get; set; }
///<summary>
/// 薪水
///</summary>
[ScriptIgnore]//使用JavaScriptSerializer序列化時(shí)不序列化此字段
[IgnoreDataMember]//使用DataContractJsonSerializer序列化時(shí)不序列化此字段
[JsonIgnore]//使用JsonConvert序列化時(shí)不序列化此字段
publicint Salary { get; set; }
///<summary>
/// 權(quán)利級(jí)別
///</summary>
[DataMember]
public Priority Priority { get; set; }
public User()
{
Urls =new List<string>();
}
}
///<summary>
/// 權(quán)利級(jí)別
///</summary>
publicenum Priority:byte
{
Lowest=0x1,
BelowNormal=0x2,
Normal=0x4,
AboveNormal=0x8,
Highest=0x16
}
}
程序的運(yùn)行結(jié)果如下:
1.使用JavaScriptSerializer序列化后的結(jié)果:{"UserId":1,"UserName":"李剛","CreateDate":"\/Date(353521211984)\/","Birthday":"\/Date(-277630788015)\/","Urls":[],"Priority":22},長(zhǎng)度:127
2.使用JavaScriptSerializer反序列化后的結(jié)果:UserId:1,UserName:李剛,CreateDate:1981-3-15 16:20:11,Priority:Highest
3.使用DataContractJsonSerializer序列化后的結(jié)果:{"Birthday":"\/Date(-277630787953+0800)\/","CreateDate":"\/Date(353521212046+0800)\/","Priority":8,"Urls":[],"UserId":1,"UserName":"李剛"},長(zhǎng)度:136
4.使用DataContractJsonSerializer反序列化后的結(jié)果:UserId:1,UserName:李剛,CreateDate:1981-3-16 0:20:12,Priority:AboveNormal
5.使用JsonConvert序列化后的結(jié)果:{"UserId":1,"UserName":"李剛","CreateDate":"1981-03-16T00:20:12.1875+08:00","Birthday":new Date(-277630787812),"Urls":[],"Priority":2},長(zhǎng)度:132
6.使用JsonConvert反序列化后的結(jié)果:UserId:1,UserName:李剛,CreateDate:1981-3-16 0:20:12,Priority:BelowNormal
7.使用JsonConvert序列化后的結(jié)果:{"UserId":1,"UserName":"周公","CreateDate":"2003-03-16T00:20:12.40625+08:00","Birthday":new Date(290362812406),"Urls":["http://office.jb51.net","https://www.jb51.net/web"],"Priority":1},長(zhǎng)度:198
8.使用Linq to JSON反序列化后的結(jié)果:["http://office.jb51.net",https://www.jb51.net/web]
總結(jié):通過(guò)上面的例子大家可以看出Newtonsoft類庫(kù)提供的JSON序列化和反序列的方式更加靈活,在實(shí)際開發(fā)中周公也一直使用Newtonsoft作為JSON序列化和反序列化的不二選擇。
到此,相信大家對(duì)“在.NET如何使用JSON作為數(shù)據(jù)交換格式”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)建站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
當(dāng)前標(biāo)題:在.NET如何使用JSON作為數(shù)據(jù)交換格式-創(chuàng)新互聯(lián)
標(biāo)題URL:http://muchs.cn/article20/djpojo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、云服務(wù)器、網(wǎng)站收錄、品牌網(wǎng)站設(shè)計(jì)、ChatGPT、網(wǎng)站維護(hù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容