asp.net how to construct a JSON string using a DataTable _ Practical tips

Source: Internet
Author: User

The example in this article describes the method by which ASP.net uses a DataTable to construct a JSON string. Share to everyone for your reference, specific as follows:

<summary>///convert DataTable to JSON///</summary>///<param name= "DTB" ></param>///<return
  S></returns> private String Dtb2json (DataTable dtb) {JavaScriptSerializer JSS = new JavaScriptSerializer ();
  System.Collections.ArrayList dic = new System.Collections.ArrayList (); foreach (DataRow Dr in DtB. Rows) {system.collections.generic.dictionary<string, object> drow = new system.collections.generic.dictionary&
   Lt;string, object> (); foreach (DataColumn dc in DTB. Columns) {Drow. ADD (DC. ColumnName, DR[DC.
   ColumnName]); DiC.
  ADD (drow); //Serialization return JSS.
Serialize (DIC); ///<summary>///Build JSON string///</summary>///<param name= "DT" ></param>///<returns>&lt ;/returns> public static string createjsonparameters (DataTable dt) {System.Text.StringBuilder sb = new System.Text.St
 Ringbuilder (); if (dt!= null && dt. Rows.Count > 0) {sb.
  Append ("["); for (int i = 0; i; Dt. Rows.Count; i++) {sb.
   Append ("{"); for (int j = 0; j < dt.) Columns.count; J + +) {//If the value is not the last one, add a comma-delimited if (J < DT). columns.count-1) {sb. Append ("/") + dt. COLUMNS[J]. Columnname.tostring () + "/": "+"/"" + dt. ROWS[I][J].
    ToString () + "/", "); ///If the value is the last character, do not add a comma else if (j = = dt. columns.count-1) {sb. Append ("/") + dt. COLUMNS[J]. Columnname.tostring () + "/": "+"/"" + dt. ROWS[I][J].
    ToString () + "/" "); }///If the last value is not added comma if (i = = dt. rows.count-1) {sb.
   Append ("}"); } else {sb.
   Append ("},"); } sb.
  Append ("]"); Return SB.
 ToString (); else {return null;}}

I hope this article will help you with ASP.net programming.

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.