DataTable and JSON string mutual transfer

Source: Internet
Author: User
Tags tojson

#regionConvert DataTable to JSON string instance method/// <summary>///Summary description of Getclasstypejosn/// </summary> Public classgetclasstypejosn:ihttphandler{/// <summary>    ///file name: DataTable and JSON string mutual transfer/// </summary>     //Usage Description Instance      Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Application/json"; Context. Response.Charset="Utf-8"; HttpRequest req=context.        Request; stringmethod = req["Method"]. Tostr ().       ToLower (); //Get Contract Details List DataTable converted to JSON string        if(Method = ="txtdate")        {            stringJSON =""; BO. MAKECONTRACTMX BLL=Newmakecontractmx (); DataSet DS=BLL.            Getdatatable (); if(ds. Tables.count >0) {JSON=tojson (ds. tables[0]); } context.            Response.Write (JSON); return; }    }    Public BOOLisreusable {Get        {            return false; }    }}   #endregion    #regionJSON string conversion to DataTable instance method PublicDataTable Jsontodatatable (JSON) {DataTable dt=todatatable (JSON); returnDT; }        #endregion    #regionDataTable converted to JSON string/// <summary>    ///DataTable object converted to JSON string/// </summary>    /// <param name= "DT" ></param>    /// <returns></returns>     Public Static stringToJson ( ThisDataTable DT) {JavaScriptSerializer JavaScriptSerializer=NewJavaScriptSerializer (); Javascriptserializer.maxjsonlength= Int32.MaxValue;//get the maximum valueArrayList ArrayList =NewArrayList (); foreach(DataRow DataRowinchdt. Rows) {Dictionary<string,Object> dictionary =Newdictionary<string,Object> ();//instantiate a collection of parameters            foreach(DataColumn DataColumninchdt. Columns) {dictionary. ADD (Datacolumn.columnname, Datarow[datacolumn.columnname].            Tostr ()); } arraylist.add (dictionary); //adding a key value to the ArrayList collection        }        returnJavascriptserializer.serialize (arrayList);//returns a JSON string    }    #endregion    #regionJson string converted to DataTable data collection/// <summary>    ///Json string converted to DataTable data collection/// </summary>    /// <param name= "JSON" ></param>    /// <returns></returns>     Public StaticDataTable todatatable ( This stringJSON) {DataTable DataTable=NewDataTable ();//instantiation ofDataTable result; Try{JavaScriptSerializer JavaScriptSerializer=NewJavaScriptSerializer (); Javascriptserializer.maxjsonlength= Int32.MaxValue;//get the maximum valueArrayList ArrayList = javascriptserializer.deserialize<arraylist>(JSON); if(Arraylist.count >0)            {                foreach(dictionary<string,Object> DictionaryincharrayList) {                    if(Dictionary. keys.count<string> () = =0) {result=dataTable; returnresult; }                    if(DataTable.Columns.Count = =0)                    {                        foreach(stringCurrentinchdictionary. Keys) {DATATABLE.COLUMNS.ADD (current, dictionary[current].                        GetType ()); }} DataRow DataRow=Datatable.newrow (); foreach(stringCurrentinchdictionary. Keys) {Datarow[current]=Dictionary[current]; } dataTable.Rows.Add (DataRow); //loop to add rows to the DataTable                }            }        }        Catch{} result=dataTable; returnresult; }    #endregion    #regionConvert to String type/// <summary>    ///Convert to String type/// </summary>    /// <param name= "S" >get the value you want to convert</param>    /// <param name= "format" >number of digits that need to be formatted</param>    /// <returns>returns a new string</returns>     Public Static stringTOSTR ( This ObjectSstringFormat ="")    {        stringresult =""; Try        {            if(Format = ="") {result=s.tostring (); }            Else{result=string. Format ("{0:"+ Format +"}", s); }        }        Catch        {        }        returnresult; }   #endregion

DataTable and JSON string mutual transfer

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.