[C #] JavaScriptSerializer Help Class

Source: Internet
Author: User

Key code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text.RegularExpressions;usingSystem.Web.Script.Serialization;namespaceyanzhiwei.dotnet3._5.utilities.common{// <summary>    /// JavaScriptSerializer Help class    // </summary>     Public Static classScriptserializerhelper {#regionTime format issues for working with JSON strings// <summary>        /// time format issues for processing jsonstring        ///<para>eg:scriptserializerhelper.parsejsontime (@ "[{' GetTime ': ' \/date (1419564257428)/'}]", " YyyyMMdd hh:mm:ss "); ==>[{' getTime ': ' 20141226 11:24:17 '}]</para>        ///<para> reference: http://www.cnphp6.com/archives/35773 </para>        // </summary>        /// <param name= "jsonstring" >json string </param>        /// <param name= "Formart" > Time formatting Type </param>        /// <returns> processed JSON string </returns>         Public Static stringParsejsontime ( This stringJsonstring,stringFormart) {if(!string. IsNullOrEmpty (jsonstring)) {jsonstring = Regex.Replace (jsonstring,@ "\\/date\ ((\d+) \) \\/", match = {DateTime _datetime =NewDateTime (1970, 1, 1); _datetime = _datetime.addmilliseconds (Long. Parse (match. GROUPS[1].                    Value)); _datetime = _datetime.tolocaltime ();return_datetime.tostring (Formart);            }); }returnjsonstring; }// <summary>        ///processing jsonstring time format problem "time format: Yyyy-mm-dd HH:mm:ss"        ///<para> reference: http://www.cnphp6.com/archives/35773 </para>        // </summary>        /// <param name= "jsonstring" >json string </param>        /// <returns> processed JSON string </returns>         Public Static stringParsejsontime ( This stringjsonstring) {returnParsejsontime (jsonstring,"Yyyy-mm-dd HH:mm:ss"); }#endregion        #regionUsing JavaScriptSerializer to serialize objects into JSON// <summary>        /// use JavaScriptSerializer to serialize objects into JSON strings        ///<para>eg:ScriptSerializerHelper.Serialize<Person> (_personlist);</para>        // </summary>        /// <typeparam name= "T" > Generics </typeparam>        /// <param name= "Entitylist" > Object collection </param>        // <returns>json</returns>         Public Static stringSerialize<t> ( ThisIenumerable<t> entitylist)whereT:class{string_jsonstring =string. Empty;if(Entitylist! =NULL) {JavaScriptSerializer _serializerhelper =NewJavaScriptSerializer (); _serializerhelper.maxjsonlength =int.                MaxValue;            _jsonstring = _serializerhelper.serialize (entitylist); }return_jsonstring; }#endregion        #regionUsing JavaScriptSerializer to deserialize a JSON string// <summary>        /// use JavaScriptSerializer to deserialize JSON string        ///<para>eg:List<Person> _result = (list<person>) scriptserializerhelper.deserialize< Person> (_jsonstring);</para>        // </summary>        /// <typeparam name= "T" > Generics </typeparam>        /// <param name= "jsonstring" ></param>        // <returns>IEnumerable</returns>         Public StaticIenumerable<t> deserialize<t> ( This stringjsonstring)whereR |class{Ienumerable<t> _list =NULL;if(!string. IsNullOrEmpty (jsonstring)) {JavaScriptSerializer _serializerhelper =NewJavaScriptSerializer ();            _list = _serializerhelper.deserialize<ienumerable<t>> (jsonstring); }return_list; }#endregion}}

Code test:

usingMicrosoft.VisualStudio.TestTools.UnitTesting;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingYanzhiwei.dotnet3._5.utilitiestests.model;namespaceyanzhiwei.dotnet3._5.utilities.common.tests{[TestClass ()] Public classscriptserializerhelpertests {[TestMethod ()] Public voidSerializetest () {Person _persona =NewPerson () {Name ="Yanzhiweia", age = ten, Address ="Shanghaia"}; Person _PERSONB =NewPerson () {Name ="Yanzhiweib", age = one, Address ="Shanghaib"}; Ilist<person> _personlist =NewList<person> ();            _personlist.add (_persona); _personlist.add (_PERSONB);string_actual = scriptserializerhelper.serialize<person> (_personlist);string_expect ="[{\" name\ ": \" Yanzhiweia\ ", \" age\ ": 10,\" address\ ": \" Shanghaia\ "},{\" name\ ": \" yanzhiweib\ ", \" age\ ": 11,\" Address\ ": \" Shanghaib\ "}]"; assert.areequal<string> (_expect, _actual); } [TestMethod ()] Public voidDeserializetest () {Person _persona =NewPerson () {Name ="Yanzhiweia", age = ten, Address ="Shanghaia"}; Person _PERSONB =NewPerson () {Name ="Yanzhiweib", age = one, Address ="Shanghaib"}; List<person> _expected =NewList<person> (); _expected.            ADD (_persona); _expected. ADD (_PERSONB);string_jsonstring ="[{' Name ': ' Yanzhiweia ', ' age ': ten, ' Address ': ' Shanghaia '},{' name ': ' Yanzhiweib ', ' age ': one, ' address ': ' Shanghaib ' }]"; List<person> _result = (list<person>) scriptserializerhelper.deserialize<person> (_jsonString);BOOL_actual = _expected. SequenceEqual (_result,NewPersoncompare ());        Assert.istrue (_actual); } [TestMethod ()] Public voidParsejsontimetest () {string_actual = Scriptserializerhelper.parsejsontime (@ "[{' GetTime ': ' \/date (1419564257428)/'}]","YyyyMMdd hh:mm:ss"); Assert.AreEqual ("[{' GetTime ': ' 20141226 11:24:17 '}]", _actual); }    } Public classpersoncompare:iequalitycomparer<person> { Public BOOLEquals (person x, person y) {return(X.age = = y.age) && (x.address = = y.address) && (x.name = y.name); } Public intGetHashCode (person obj) {returnObj.        Name.gethashcode (); }    }}
Test results:
Hope to be helpful! Thank you

[C #] JavaScriptSerializer Help Class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.