C # Implements a method of converting JSON to a DataTable

Source: Internet
Author: User
This example describes the C # implementation of the method of converting JSON to a DataTable. Share to everyone for your reference. The implementation method is as follows:

#region convert JSON to datatable///<summary>///convert JSON to datatable///</summary>///<param name= "StrJson" > Obtained json</param>///<returns></returns>private DataTable jsontodatatable (string Strjson) {// Convert JSON format Strjson = strjson.replace (", \" "," *\ "). Replace ("\": "," \ "#").    ToString ();    Remove the table name var RG = new Regex (@ "(? <={) [^:]+ (? =:\[)", regexoptions.ignorecase); String strName = RG. Match (Strjson).    Value;    DataTable TB = null;    Remove table name Strjson = strjson.substring (Strjson.indexof ("[") + 1);    Strjson = strjson.substring (0, Strjson.indexof ("]"));    Get Data RG = new Regex (@ "(? <={) [^}]+ (? =})"); MatchCollection MC = RG.    Matches (Strjson); for (int i = 0; I < MC. Count; i++) {string strrow = Mc[i]. Value; string[] strrows = strrow.split (' * ');     CREATE TABLE if (TB = = NULL) {TB = new DataTable (); Tb.     TableName = StrName;  foreach (String str in strrows) {var dc = new DataColumn (); string[] Strcell = str. Split (' # '); if (Strcell[0]. Substring (0, 1) = = "\" ") {int a = strcell[0].      Length; dc. ColumnName = strcell[0].  Substring (1, a-2); } else {DC.  ColumnName = strcell[0]; } TB.     Columns.Add (DC); } TB. AcceptChanges (); }//Add content to DataRow dr = TB. NewRow (); for (int r = 0; r < strrows.length; r++) {Dr[r] = Strrows[r]. Split (' # ') [1]. Trim (). Replace (",", ","). Replace (":", ":"). Replace ("\" "," ");} Tb. Rows.Add (DR); Tb.    AcceptChanges (); } return TB; #endregion

Hopefully this article will help you with your C # programming.

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.