C#對JSON與對象的序列化與反序列化_第1頁
C#對JSON與對象的序列化與反序列化_第2頁
C#對JSON與對象的序列化與反序列化_第3頁
C#對JSON與對象的序列化與反序列化_第4頁
C#對JSON與對象的序列化與反序列化_第5頁
已閱讀5頁,還剩1頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

第C#對JSON與對象的序列化與反序列化一、利用Web服務(wù)中的JavaScriptSerializer類

System.Web.Script.Serialization空間,位于System.Web.extensions.dll中。

JavaScriptSerializerjss=newJavaScriptSerializer();

Console.WriteLine(jss.MaxJsonLength);//默認接受最大的長度是2097152這個是接受JSON字符串的最大長度,超長會有什么后果呢?試下

Personp=newPerson(1,"關(guān)羽",21);

//序列化

stringjson=jss.Serialize(p);

Console.WriteLine(json);//輸出{"Id":1,"Name":"關(guān)羽","Age":21}`這就是Json格式了

//反序列化:1、Deserialize泛型寫法

Personp2=jss.Deserialize("{\"Id\":1,\"Name\":\"關(guān)羽\",\"Age\":21}");

Console.WriteLine(p2.Id+""+p2.Name+""+p2.Age);//輸出1關(guān)羽21

//反序列化:2、Deserialize的非泛型寫法

Personp3=jss.Deserialize("{\"Id\":1,\"Name\":\"關(guān)羽\",\"Age\":21}",typeof(Person))asPerson;//注意這個方法返回的是object類,因此要強制轉(zhuǎn)換成Person類

Console.WriteLine(p3.Id+""+p3.Name+""+p3.Age);//同樣輸出1關(guān)羽21

//反序列化:3、將Json字符轉(zhuǎn)換為Object類型

objectobj=jss.DeserializeObject("{\"Id\":1,\"Name\":\"關(guān)羽\",\"Age\":21}");

Personp4=jss.ConvertToType(obj);

Console.WriteLine(p4.Name);

Personp5=jss.ConvertToType(obj,typeof(Person))asPerson;

Console.WriteLine(p5.Name);

publicclassPerson

publicPerson()

publicPerson(intid,stringname,intage)

this.Id=id;

this.Name=name;

this.Age=age;

publicintId{get;set;}

publicstringName{get;set;}

publicintAge{get;set;}

}

二、利用WCF中的JSON類:DataContractJsonSerializer

System.Runtine.Serialization命名空間中,位于System.Runtine,Serialization.dll中。

voidMain()

DataContractJsonSerializerserializer=newDataContractJsonSerializer(typeof(Person));

//最常用的兩個方法

//反序列化

stringstr="{\"Id\":1,\"Name\":\"劉備\",\"Age\":\"23\"}";

Personp;

using(MemoryStreamms=newMemoryStream(Encoding.UTF8.GetBytes(str)))//構(gòu)造函數(shù)能夠接受Stream參數(shù),因此你可以用內(nèi)存流,文件流等等創(chuàng)建

p=serializer.ReadObject(ms)asPerson;

Console.WriteLine(p.Name);//輸出劉備

//反序列化

Personp2=newPerson(2,"關(guān)羽",23);

byte[]byteArr;

using(MemoryStreamms=newMemoryStream())

serializer.WriteObject(ms,p2);

byteArr=ms.ToArray();

Console.WriteLine(Encoding.UTF8.GetString(byteArr));//輸出{"Age":23,"Id":1,"Name":"關(guān)羽"}

[DataContract]//對于使用DataContractJsonSerializer類而言,該屬性是必須的

publicclassPerson

publicPerson(intid,stringname,intage)

Id=id;

Age=age;

Name=name;

[DataMember]//對于使用DataContractJsonSerializer類而言,該屬性是必須的

publicintId

get;

set;

[DataMember]

publicstringName

get;

set;

[DataMember]

publicintAge

get;

set;

}

三、轉(zhuǎn)換規(guī)則

String,char=stringDBNull,null=null,nullBoolean=trur/falseint,Double,...=NumberDateTime..=\/Date(刻度數(shù))\/,即用\/包含。

eg:\/Data\/枚舉數(shù)=整數(shù)值eg:Color.Red=3List,Arrary,ArrayLIst,=JSON數(shù)組

eg:newString[]{2,2,3}=[1,2,3]Dictionary,HashTable=JSON對象

eg:newDictionary{{1,a},{2,b},{3,c}}={1:a,2:b,3:c}具有公共實例屬性或字段的非抽象類=JSON對象

注意:公共只寫屬性,以及標記[ScriptIgnore]或[IgnoreDataMember]的屬性、字段或?qū)傩詫⒈缓雎浴?/p>

eg:{1:a,2:b,3:c}好包括_type屬性。

四、利用Json.Net三方工具

/json

Json.Net介紹:///article/247911.htm

五、JSON序列化過程中日期的處理

1、在c#后臺進行處理:通過正則表示式

System.Web.Script.Serialization.JavaScriptSerializerjs=newSystem.Web.Script.Serialization.JavaScriptSerializer();

Listlist=newList();

list.Add(newStudent()

age=10,

date=DateTime.Now,

name="宋興柱是個好孩\"子,這里\"有英文逗號"

varstr=js.Serialize(list);

str=Regex.Replace(str,@"\\/Date\((\d+)\)\\/",match=

DateTimedt=newDateTime(1970,1,1);

dt=dt.AddMilliseconds(long.Parse(match.Groups[1].Value)).ToLocalTime();

returndt.ToString("yyyy-MM-ddHH:mm:ss");

});

原本內(nèi)容:[{age:10,date:\/Date(1404098342309)\/,name:宋興柱是個好孩\子,這里\有英文逗號}]

顯示結(jié)果:[{age:10,date:2014-06-3011:22:15,name:宋興柱是個好孩\子,這里\有英文逗號}]

2、Json.Net中使用IsoDateTimeConverter格式自定義

IsoDateTimeConverterdtConverter=newIsoDateTimeConverter{DateTimeFormat="yyyy'年'MM'月'dd'日'"};

stringjson=JsonConvert.SerializeObject(jack,dtConverter);

參考:Json.Net高級用法

3、在JS中進行處理:

接收json數(shù)據(jù),日期格式為:\/Date(1414078309687)\/

varvalue="/Date(1414078309687)/";

varda=eval('new'+value.replace('/','','g'));

varda=value.replace(/\/Date\((\d+)\)\//gi,'$1');////通過正則拿到里面數(shù)。g全局i不區(qū)分大小寫

da.toLocaleDateString()//2014/10/23

da.toLocaleTimeString()//下午11:31:49

六、Json.NET對比NETSerializers

性能對比:

功能對比:

特性Json.NetDataContractJsonSerializerJavaScriptSerializerJson支持支持支持Bson支持不支持不支持JsonSchema支持不支持不支持.Net2.0支持不支持不支持.Net3.5支持支持支持.Net4

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論