Json.net 常用使用小结(推荐)
Json.net常用使用小结(推荐)
usingSystem; usingSystem.Linq; usingSystem.Collections.Generic; namespacemicrostore { publicinterfaceIPerson { stringFirstName { get; set; } stringLastName { get; set; } DateTimeBirthDate { get; set; } } publicclassEmployee:IPerson { publicstringFirstName { get; set; } publicstringLastName { get; set; } publicDateTimeBirthDate { get; set; } publicstringDepartment { get; set; } publicstringJobTitle { get; set; } } publicclassPersonConverter:Newtonsoft.Json.Converters.CustomCreationConverter<IPerson> { //重写abstractclassCustomCreationConverter<T>的Create方法 publicoverrideIPersonCreate(TypeobjectType) { returnnewEmployee(); } } publicpartialclasstestjson:System.Web.UI.Page { protectedvoidPage_Load(objectsender,EventArgse) { //if(!IsPostBack) //TestJson(); } #region序列化 publicstringTestJsonSerialize() { Productproduct=newProduct(); product.Name="Apple"; product.Expiry=DateTime.Now.AddDays(3).ToString("yyyy-MM-ddhh:mm:ss"); product.Price=3.99M; //product.Sizes=newstring[]{"Small","Medium","Large"}; //stringjson=Newtonsoft.Json.JsonConvert.SerializeObject(product);//没有缩进输出 stringjson=Newtonsoft.Json.JsonConvert.SerializeObject(product,Newtonsoft.Json.Formatting.Indented); //stringjson=Newtonsoft.Json.JsonConvert.SerializeObject( //product, //Newtonsoft.Json.Formatting.Indented, //newNewtonsoft.Json.JsonSerializerSettings{NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore} //); returnstring.Format("<p>{0}</p>",json); } publicstringTestListJsonSerialize() { Productproduct=newProduct(); product.Name="Apple"; product.Expiry=DateTime.Now.AddDays(3).ToString("yyyy-MM-ddhh:mm:ss"); product.Price=3.99M; product.Sizes=newstring[]{"Small","Medium","Large"}; List<Product>plist=newList<Product>(); plist.Add(product); plist.Add(product); stringjson=Newtonsoft.Json.JsonConvert.SerializeObject(plist,Newtonsoft.Json.Formatting.Indented); returnstring.Format("<p>{0}</p>",json); } #endregion #region反序列化 publicstringTestJsonDeserialize() { stringstrjson="{\"Name\":\"Apple\",\"Expiry\":\"2014-05-0310:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}"; Productp=Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(strjson); stringtemplate=@"<p><ul> <li>{0}</li> <li>{1}</li> <li>{2}</li> <li>{3}</li> </ul></p>"; returnstring.Format(template,p.Name,p.Expiry,p.Price.ToString(),string.Join(",",p.Sizes)); } publicstringTestListJsonDeserialize() { stringstrjson="{\"Name\":\"Apple\",\"Expiry\":\"2014-05-0310:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}"; List<Product>plist=Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(string.Format("[{0},{1}]",strjson,strjson)); stringtemplate=@"<p><ul> <li>{0}</li> <li>{1}</li> <li>{2}</li> <li>{3}</li> </ul></p>"; System.Text.StringBuilderstrb=newSystem.Text.StringBuilder(); plist.ForEach(x=> strb.AppendLine( string.Format(template,x.Name,x.Expiry,x.Price.ToString(),string.Join(",",x.Sizes)) ) ); returnstrb.ToString(); } #endregion #region自定义反序列化 publicstringTestListCustomDeserialize() { stringstrJson="[{\"FirstName\":\"Maurice\",\"LastName\":\"Moss\",\"BirthDate\":\"1981-03-08T00:00Z\",\"Department\":\"IT\",\"JobTitle\":\"Support\"},{\"FirstName\":\"Jen\",\"LastName\":\"Barber\",\"BirthDate\":\"1985-12-10T00:00Z\",\"Department\":\"IT\",\"JobTitle\":\"Manager\"}]"; List<IPerson>people=Newtonsoft.Json.JsonConvert.DeserializeObject<List<IPerson>>(strJson,newPersonConverter()); IPersonperson=people[0]; stringtemplate=@"<p><ul> <li>当前List<IPerson>[x]对象类型:{0}</li> <li>FirstName:{1}</li> <li>LastName:{2}</li> <li>BirthDate:{3}</li> <li>Department:{4}</li> <li>JobTitle:{5}</li> </ul></p>"; System.Text.StringBuilderstrb=newSystem.Text.StringBuilder(); people.ForEach(x=> strb.AppendLine( string.Format( template, person.GetType().ToString(), x.FirstName, x.LastName, x.BirthDate.ToString(), ((Employee)x).Department, ((Employee)x).JobTitle ) ) ); returnstrb.ToString(); } #endregion #region反序列化成Dictionary publicstringTestDeserialize2Dic() { //stringjson=@"{""key1"":""zhangsan"",""key2"":""lisi""}"; //stringjson="{\"key1\":\"zhangsan\",\"key2\":\"lisi\"}"; stringjson="{key1:\"zhangsan\",key2:\"lisi\"}"; Dictionary<string,string>dic=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(json); stringtemplate=@"<li>key:{0},value:{1}</li>"; System.Text.StringBuilderstrb=newSystem.Text.StringBuilder(); strb.Append("Dictionary<string,string>长度"+dic.Count.ToString()+"<ul>"); dic.AsQueryable().ToList().ForEach(x=> { strb.AppendLine(string.Format(template,x.Key,x.Value)); }); strb.Append("</ul>"); returnstrb.ToString(); } #endregion #regionNullValueHandling特性 publicclassMovie { publicstringName{get;set;} publicstringDescription{get;set;} publicstringClassification{get;set;} publicstringStudio{get;set;} publicDateTime?ReleaseDate{get;set;} publicList<string>ReleaseCountries{get;set;} } ///<summary> ///完整序列化输出 ///</summary> publicstringCommonSerialize() { Moviemovie=newMovie(); movie.Name="BadBoysIII"; movie.Description="It'snoBadBoys"; stringincluded=Newtonsoft.Json.JsonConvert.SerializeObject( movie, Newtonsoft.Json.Formatting.Indented,//缩进 newNewtonsoft.Json.JsonSerializerSettings{} ); returnincluded; } ///<summary> ///忽略空(Null)对象输出 ///</summary> ///<returns></returns> publicstringIgnoredSerialize() { Moviemovie=newMovie(); movie.Name="BadBoysIII"; movie.Description="It'snoBadBoys"; stringincluded=Newtonsoft.Json.JsonConvert.SerializeObject( movie, Newtonsoft.Json.Formatting.Indented,//缩进 newNewtonsoft.Json.JsonSerializerSettings{NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore} ); returnincluded; } #endregion publicclassProduct { publicstringName{get;set;} publicstringExpiry{get;set;} publicDecimalPrice{get;set;} publicstring[]Sizes{get;set;} } #regionDefaultValueHandling默认值 publicclassInvoice { publicstringCompany{get;set;} publicdecimalAmount{get;set;} //falseisdefaultvalueofbool publicboolPaid{get;set;} //nullisdefaultvalueofnullable publicDateTime?PaidDate{get;set;} //customizedefaultvalues [System.ComponentModel.DefaultValue(30)] publicintFollowUpDays{get;set;} [System.ComponentModel.DefaultValue("")] publicstringFollowUpEmailAddress{get;set;} } publicvoidGG() { Invoiceinvoice=newInvoice { Company="AcmeLtd.", Amount=50.0m, Paid=false, FollowUpDays=30, FollowUpEmailAddress=string.Empty, PaidDate=null }; stringincluded=Newtonsoft.Json.JsonConvert.SerializeObject( invoice, Newtonsoft.Json.Formatting.Indented, newNewtonsoft.Json.JsonSerializerSettings{} ); //{ //"Company":"AcmeLtd.", //"Amount":50.0, //"Paid":false, //"PaidDate":null, //"FollowUpDays":30, //"FollowUpEmailAddress":"" //} stringignored=Newtonsoft.Json.JsonConvert.SerializeObject( invoice, Newtonsoft.Json.Formatting.Indented, newNewtonsoft.Json.JsonSerializerSettings{DefaultValueHandling=Newtonsoft.Json.DefaultValueHandling.Ignore} ); //{ //"Company":"AcmeLtd.", //"Amount":50.0 //} } #endregion #regionJsonIgnoreAttributeandDataMemberAttribute特性 publicstringOutIncluded() { Carcar=newCar { Model="zhangsan", Year=DateTime.Now, Features=newList<string>{"aaaa","bbbb","cccc"}, LastModified=DateTime.Now.AddDays(5) }; returnNewtonsoft.Json.JsonConvert.SerializeObject(car,Newtonsoft.Json.Formatting.Indented); } publicstringOutIncluded2() { Computercom=newComputer { Name="zhangsan", SalePrice=3999m, Manufacture="red", StockCount=5, WholeSalePrice=34m, NextShipmentDate=DateTime.Now.AddDays(5) }; returnNewtonsoft.Json.JsonConvert.SerializeObject(com,Newtonsoft.Json.Formatting.Indented); } publicclassCar { //includedinJSON publicstringModel{get;set;} publicDateTimeYear{get;set;} publicList<string>Features{get;set;} //ignored [Newtonsoft.Json.JsonIgnore] publicDateTimeLastModified{get;set;} } //在nt3.5中需要添加System.Runtime.Serialization.dll引用 [System.Runtime.Serialization.DataContract] publicclassComputer { //includedinJSON [System.Runtime.Serialization.DataMember] publicstringName{get;set;} [System.Runtime.Serialization.DataMember] publicdecimalSalePrice{get;set;} //ignored publicstringManufacture{get;set;} publicintStockCount{get;set;} publicdecimalWholeSalePrice{get;set;} publicDateTimeNextShipmentDate{get;set;} } #endregion #regionIContractResolver特性 publicclassBook { publicstringBookName{get;set;} publicdecimalBookPrice{get;set;} publicstringAuthorName{get;set;} publicintAuthorAge{get;set;} publicstringAuthorCountry{get;set;} } publicvoidKK() { Bookbook=newBook { BookName="TheGatheringStorm", BookPrice=16.19m, AuthorName="BrandonSanderson", AuthorAge=34, AuthorCountry="UnitedStatesofAmerica" }; stringstartingWithA=Newtonsoft.Json.JsonConvert.SerializeObject( book,Newtonsoft.Json.Formatting.Indented, newNewtonsoft.Json.JsonSerializerSettings{ContractResolver=newDynamicContractResolver('A')} ); //{ //"AuthorName":"BrandonSanderson", //"AuthorAge":34, //"AuthorCountry":"UnitedStatesofAmerica" //} stringstartingWithB=Newtonsoft.Json.JsonConvert.SerializeObject( book, Newtonsoft.Json.Formatting.Indented, newNewtonsoft.Json.JsonSerializerSettings{ContractResolver=newDynamicContractResolver('B')} ); //{ //"BookName":"TheGatheringStorm", //"BookPrice":16.19 //} } publicclassDynamicContractResolver:Newtonsoft.Json.Serialization.DefaultContractResolver { privatereadonlychar_startingWithChar; publicDynamicContractResolver(charstartingWithChar) { _startingWithChar=startingWithChar; } protectedoverrideIList<Newtonsoft.Json.Serialization.JsonProperty>CreateProperties(Typetype,Newtonsoft.Json.MemberSerializationmemberSerialization) { IList<Newtonsoft.Json.Serialization.JsonProperty>properties=base.CreateProperties(type,memberSerialization); //onlyserializerpropertiesthatstartwiththespecifiedcharacter properties= properties.Where(p=>p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList(); returnproperties; } } #endregion //... } } #regionSerializingPartialJSONFragmentExample publicclassSearchResult { publicstringTitle{get;set;} publicstringContent{get;set;} publicstringUrl{get;set;} } publicstringSerializingJsonFragment() { #region stringgoogleSearchText=@"{ 'responseData':{ 'results':[{ 'GsearchResultClass':'GwebSearch', 'unescapedUrl':'http://en.wikipedia.org/wiki/Paris_Hilton', 'url':'http://en.wikipedia.org/wiki/Paris_Hilton', 'visibleUrl':'en.wikipedia.org', 'cacheUrl':'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org', 'title':'<b>ParisHilton</b>-Wikipedia,thefreeencyclopedia', 'titleNoFormatting':'ParisHilton-Wikipedia,thefreeencyclopedia', 'content':'[1]In2006,shereleasedherdebutalbum...' }, { 'GsearchResultClass':'GwebSearch', 'unescapedUrl':'http://www.imdb.com/name/nm0385296/', 'url':'http://www.imdb.com/name/nm0385296/', 'visibleUrl':'www.imdb.com', 'cacheUrl':'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com', 'title':'<b>ParisHilton</b>', 'titleNoFormatting':'ParisHilton', 'content':'Self:Zoolander.Socialite<b>ParisHilton</b>...' }], 'cursor':{ 'pages':[{ 'start':'0', 'label':1 }, { 'start':'4', 'label':2 }, { 'start':'8', 'label':3 }, { 'start':'12', 'label':4 }], 'estimatedResultCount':'59600000', 'currentPageIndex':0, 'moreResultsUrl':'http://www.google.com/search?oe=utf8&ie=utf8...' } }, 'responseDetails':null, 'responseStatus':200 }"; #endregion Newtonsoft.Json.Linq.JObjectgoogleSearch=Newtonsoft.Json.Linq.JObject.Parse(googleSearchText); //getJSONresultobjectsintoalist List<Newtonsoft.Json.Linq.JToken>listJToken=googleSearch["responseData"]["results"].Children().ToList(); System.Text.StringBuilderstrb=newSystem.Text.StringBuilder(); stringtemplate=@"<ul> <li>Title:{0}</li> <li>Content:{1}</li> <li>Url:{2}</li> </ul>"; listJToken.ForEach(x=> { //serializeJSONresultsinto.NETobjects SearchResultsearchResult=Newtonsoft.Json.JsonConvert.DeserializeObject<SearchResult>(x.ToString()); strb.AppendLine(string.Format(template,searchResult.Title,searchResult.Content,searchResult.Url)); }); returnstrb.ToString(); } #endregion #regionShouldSerialize publicclassCC { publicstringName{get;set;} publicCCManager{get;set;} //http://msdn.microsoft.com/en-us/library/53b8022e.aspx publicboolShouldSerializeManager() { //don'tserializetheManagerpropertyifanemployeeistheirownmanager return(Manager!=this); } } publicstringShouldSerializeTest() { //createEmployeemike CCmike=newCC(); mike.Name="MikeManager"; //createEmployeejoe CCjoe=newCC(); joe.Name="JoeEmployee"; joe.Manager=mike;//setjoe'Manager=mike //mikeishisownmanager //ShouldSerializewillskipthisproperty mike.Manager=mike; returnNewtonsoft.Json.JsonConvert.SerializeObject(new[]{joe,mike},Newtonsoft.Json.Formatting.Indented); } #endregion //驼峰结构输出(小写打头,后面单词大写) publicstringJJJ() { Productproduct=newProduct { Name="Widget", Expiry=DateTime.Now.ToString(), Price=9.99m, Sizes=new[]{"Small","Medium","Large"} }; stringjson=Newtonsoft.Json.JsonConvert.SerializeObject( product, Newtonsoft.Json.Formatting.Indented, newNewtonsoft.Json.JsonSerializerSettings{ContractResolver=newNewtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()} ); returnjson; //{ //"name":"Widget", //"expiryDate":"2010-12-20T18:01Z", //"price":9.99, //"sizes":[ //"Small", //"Medium", //"Large" //] //} } #regionITraceWriter publicclassStaff { publicstringName{get;set;} publicList<string>Roles{get;set;} publicDateTimeStartDate{get;set;} } publicvoidKKKK() { Staffstaff=newStaff(); staff.Name="ArnieAdmin"; staff.Roles=newList<string>{"Administrator"}; staff.StartDate=newDateTime(2000,12,12,12,12,12,DateTimeKind.Utc); Newtonsoft.Json.Serialization.ITraceWritertraceWriter=newNewtonsoft.Json.Serialization.MemoryTraceWriter(); Newtonsoft.Json.JsonConvert.SerializeObject( staff, newNewtonsoft.Json.JsonSerializerSettings { TraceWriter=traceWriter, Converters={newNewtonsoft.Json.Converters.JavaScriptDateTimeConverter()} } ); Console.WriteLine(traceWriter); //2012-11-11T12:08:42.761InfoStartedserializingNewtonsoft.Json.Tests.Serialization.Staff.Path''. //2012-11-11T12:08:42.785InfoStartedserializingSystem.DateTimewithconverterNewtonsoft.Json.Converters.JavaScriptDateTimeConverter.Path'StartDate'. //2012-11-11T12:08:42.791InfoFinishedserializingSystem.DateTimewithconverterNewtonsoft.Json.Converters.JavaScriptDateTimeConverter.Path'StartDate'. //2012-11-11T12:08:42.797InfoStartedserializingSystem.Collections.Generic.List`1[System.String].Path'Roles'. //2012-11-11T12:08:42.798InfoFinishedserializingSystem.Collections.Generic.List`1[System.String].Path'Roles'. //2012-11-11T12:08:42.799InfoFinishedserializingNewtonsoft.Json.Tests.Serialization.Staff.Path''. //2013-05-18T21:38:11.255VerboseSerializedJSON: //{ //"Name":"ArnieAdmin", //"StartDate":newDate( //976623132000 //), //"Roles":[ //"Administrator" //] //} } #endregion publicstringTestReadJsonFromFile() { Linq2Jsonl2j=newLinq2Json(); Newtonsoft.Json.Linq.JObjectjarray=l2j.GetJObject4(); returnjarray.ToString(); } usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; namespacemicrostore { publicclassLinq2Json { #regionGetJObject //ParsingaJSONObjectfromtext publicNewtonsoft.Json.Linq.JObjectGetJObject() { stringjson=@"{ CPU:'Intel', Drives:[ 'DVDread/writer', '500gigabyteharddrive' ] }"; Newtonsoft.Json.Linq.JObjectjobject=Newtonsoft.Json.Linq.JObject.Parse(json); returnjobject; } /* *//example:=> * Linq2Jsonl2j=newLinq2Json(); Newtonsoft.Json.Linq.JObjectjobject=l2j.GetJObject2(Server.MapPath("json/Person.json")); //returnNewtonsoft.Json.JsonConvert.SerializeObject(jobject,Newtonsoft.Json.Formatting.Indented); returnjobject.ToString(); */ //LoadingJSONfromafile publicNewtonsoft.Json.Linq.JObjectGetJObject2(stringjsonPath) { using(System.IO.StreamReaderreader=System.IO.File.OpenText(jsonPath)) { Newtonsoft.Json.Linq.JObjectjobject=(Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(newNewtonsoft.Json.JsonTextReader(reader)); returnjobject; } } //CreatingJObject publicNewtonsoft.Json.Linq.JObjectGetJObject3() { List<Post>posts=GetPosts(); Newtonsoft.Json.Linq.JObjectjobject=Newtonsoft.Json.Linq.JObject.FromObject(new { channel=new { title="JamesNewton-King", link="http://james.newtonking.com", description="JamesNewton-King'sblog.", item= frompinposts orderbyp.Title selectnew { title=p.Title, description=p.Description, link=p.Link, category=p.Category } } }); returnjobject; } /* { "channel":{ "title":"JamesNewton-King", "link":"http://james.newtonking.com", "description":"JamesNewton-King'sblog.", "item":[{ "title":"jewron", "description":"4546fds", "link":"http://www.baidu.com", "category":"jhgj" }, { "title":"jofdsn", "description":"mdsfan", "link":"http://www.baidu.com", "category":"6546" }, { "title":"jokjn", "description":"m3214an", "link":"http://www.baidu.com", "category":"hg425" }, { "title":"jon", "description":"man", "link":"http://www.baidu.com", "category":"goodman" }] } } */ //CreatingJObject publicNewtonsoft.Json.Linq.JObjectGetJObject4() { List<Post>posts=GetPosts(); Newtonsoft.Json.Linq.JObjectrss=newNewtonsoft.Json.Linq.JObject( newNewtonsoft.Json.Linq.JProperty("channel", newNewtonsoft.Json.Linq.JObject( newNewtonsoft.Json.Linq.JProperty("title","JamesNewton-King"), newNewtonsoft.Json.Linq.JProperty("link","http://james.newtonking.com"), newNewtonsoft.Json.Linq.JProperty("description","JamesNewton-King'sblog."), newNewtonsoft.Json.Linq.JProperty("item", newNewtonsoft.Json.Linq.JArray( frompinposts orderbyp.Title selectnewNewtonsoft.Json.Linq.JObject( newNewtonsoft.Json.Linq.JProperty("title",p.Title), newNewtonsoft.Json.Linq.JProperty("description",p.Description), newNewtonsoft.Json.Linq.JProperty("link",p.Link), newNewtonsoft.Json.Linq.JProperty("category", newNewtonsoft.Json.Linq.JArray( fromcinp.Category selectnewNewtonsoft.Json.Linq.JValue(c) ) ) ) ) ) ) ) ); returnrss; } /* { "channel":{ "title":"JamesNewton-King", "link":"http://james.newtonking.com", "description":"JamesNewton-King'sblog.", "item":[{ "title":"jewron", "description":"4546fds", "link":"http://www.baidu.com", "category":["j","h","g","j"] }, { "title":"jofdsn", "description":"mdsfan", "link":"http://www.baidu.com", "category":["6","5","4","6"] }, { "title":"jokjn", "description":"m3214an", "link":"http://www.baidu.com", "category":["h","g","4","2","5"] }, { "title":"jon", "description":"man", "link":"http://www.baidu.com", "category":["g","o","o","d","m","a","n"] }] } } */ publicclassPost { publicstringTitle{get;set;} publicstringDescription{get;set;} publicstringLink{get;set;} publicstringCategory{get;set;} } privateList<Post>GetPosts() { List<Post>listp=newList<Post>() { newPost{Title="jon",Description="man",Link="http://www.baidu.com",Category="goodman"}, newPost{Title="jofdsn",Description="mdsfan",Link="http://www.baidu.com",Category="6546"}, newPost{Title="jewron",Description="4546fds",Link="http://www.baidu.com",Category="jhgj"}, newPost{Title="jokjn",Description="m3214an",Link="http://www.baidu.com",Category="hg425"} }; returnlistp; } #endregion #regionGetJArray /* *//example:=> * Linq2Jsonl2j=newLinq2Json(); Newtonsoft.Json.Linq.JArrayjarray=l2j.GetJArray(); returnNewtonsoft.Json.JsonConvert.SerializeObject(jarray,Newtonsoft.Json.Formatting.Indented); //returnjarray.ToString(); */ //ParsingaJSONArrayfromtext publicNewtonsoft.Json.Linq.JArrayGetJArray() { stringjson=@"[ 'Small', 'Medium', 'Large' ]"; Newtonsoft.Json.Linq.JArrayjarray=Newtonsoft.Json.Linq.JArray.Parse(json); returnjarray; } //CreatingJArray publicNewtonsoft.Json.Linq.JArrayGetJArray2() { Newtonsoft.Json.Linq.JArrayarray=newNewtonsoft.Json.Linq.JArray(); Newtonsoft.Json.Linq.JValuetext=newNewtonsoft.Json.Linq.JValue("Manualtext"); Newtonsoft.Json.Linq.JValuedate=newNewtonsoft.Json.Linq.JValue(newDateTime(2000,5,23)); //addtoJArray array.Add(text); array.Add(date); returnarray; } #endregion //待续... } }
测试效果:
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="testjson.aspx.cs"Inherits="microstore.testjson"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <title></title> <styletype="text/css"> body{font-family:Arial,微软雅黑;font-size:14px;} a{text-decoration:none;color:#333;} a:hover{text-decoration:none;color:#f00;} </style> </head> <body> <formid="form1"runat="server"> <h3>序列化对象</h3> 表现1:<br/> <%=TestJsonSerialize()%> <%=TestListJsonSerialize()%> 表现2:<br/> <%=TestListJsonSerialize2()%> <hr/> <h3>反序列化对象</h3> <p>单个对象</p> <%=TestJsonDeserialize()%> <p>多个对象</p> <%=TestListJsonDeserialize()%> <p>反序列化成数据字典Dictionary</p> <%=TestDeserialize2Dic()%> <hr/> <h3>自定义反序列化</h3> <%=TestListCustomDeserialize()%> <hr/> <h3>序列化输出的忽略特性</h3> NullValueHandling特性忽略=><br/> <%=CommonSerialize()%><br/> <%=IgnoredSerialize()%><br/><br/> 属性标记忽略=><br/> <%=OutIncluded()%><br/> <%=OutIncluded2()%> <hr/> <h3>SerializingPartialJSONFragments</h3> <%=SerializingJsonFragment()%> <hr/> <h3>ShouldSerialize</h3> <%=ShouldSerializeTest()%><br/> <%=JJJ()%><br/><br/> <%=TestReadJsonFromFile()%> </form> </body> </html>
显示:
序列化对象
表现1:
{"Name":"Apple","Expiry":"2014-05-0402:08:58","Price":3.99,"Sizes":null} [{"Name":"Apple","Expiry":"2014-05-0402:08:58","Price":3.99,"Sizes":["Small","Medium","Large"]},{"Name":"Apple","Expiry":"2014-05-0402:08:58","Price":3.99,"Sizes":["Small","Medium","Large"]}]
表现2:
[{"Name":"Apple","Expiry":"2014-05-0402:08:58","Price":3.99,"Sizes":["Small","Medium","Large"]},{"Name":"Apple","Expiry":"2014-05-0402:08:58","Price":3.99,"Sizes":["Small","Medium","Large"]}]
反序列化对象
单个对象
•Apple
•2014-05-0310:20:59
•3.99
•Small,Medium,Large
多个对象
•Apple
•2014-05-0310:20:59
•3.99
•Small,Medium,Large
•Apple
•2014-05-0310:20:59
•3.99
•Small,Medium,Large
反序列化成数据字典Dictionary
Dictionary长度2
•key:key1,value:zhangsan
•key:key2,value:lisi
---------------------------------------------------------------
自定义反序列化
•当前List[x]对象类型:microstore.Employee
•FirstName:Maurice
•LastName:Moss
•BirthDate:1981-3-80:00:00
•Department:IT
•JobTitle:Support
•当前List[x]对象类型:microstore.Employee
•FirstName:Jen
•LastName:Barber
•BirthDate:1985-12-100:00:00
•Department:IT
•JobTitle:Manager
-------------------------------------------------------------
序列化输出的忽略特性
NullValueHandling特性忽略=>
{"Name":"BadBoysIII","Description":"It'snoBadBoys","Classification":null,"Studio":null,"ReleaseDate":null,"ReleaseCountries":null}
{"Name":"BadBoysIII","Description":"It'snoBadBoys"}
属性标记忽略=>
{"Model":"zhangsan","Year":"2014-05-01T02:08:58.671875+08:00","Features":["aaaa","bbbb","cccc"]}
{"Name":"zhangsan","SalePrice":3999.0}
-----------------------------------------------------------------
SerializingPartialJSONFragments
•Title:ParisHilton-Wikipedia,thefreeencyclopedia
•Content:[1]In2006,shereleasedherdebutalbum...
•Url:http://en.wikipedia.org/wiki/Paris_Hilton
•Title:ParisHilton
•Content:Self:Zoolander.SocialiteParisHilton...
•Url:http://www.imdb.com/name/nm0385296/
--------------------------------------------------------------------------------
ShouldSerialize
[{"Name":"JoeEmployee","Manager":{"Name":"MikeManager"}},{"Name":"MikeManager"}]
{"name":"Widget","expiry":"2014-5-12:08:58","price":9.99,"sizes":["Small","Medium","Large"]}
{"channel":{"title":"JamesNewton-King","link":"http://james.newtonking.com","description":"JamesNewton-King'sblog.","item":[{"title":"jewron","description":"4546fds","link":"http://www.baidu.com","category":["j","h","g","j"]},{"title":"jofdsn","description":"mdsfan","link":"http://www.baidu.com","category":["6","5","4","6"]},{"title":"jokjn","description":"m3214an","link":"http://www.baidu.com","category":["h","g","4","2","5"]},{"title":"jon","description":"man","link":"http://www.baidu.com","category":["g","o","o","d","m","a","n"]}]}}
以上这篇Json.net常用使用小结(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。