C # parses Json into datetable
The #region parses the JSON into datetable//<summary>//To parse JSON into datetable. Json data format such as:///{Table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}//</S ummary>//<param name= "Strjson" > Json string to parse </param>//<returns> return DATETABLE&L T;/returns> Public DataTable jsontodatatable (string Strjson) {//Remove table name var RG = New Regex (@ "(? <={) [^:]+ (? =:\[)", regexoptions.ignorecase); String strName = RG. Match (Strjson). Value; DataTable TB = null; The data is empty to return if (Strjson.trim (). Length = = 0) {return TB; }//Check if Strjson is a JSON string if (! Jsonsplit.isjson (Strjson)) {return TB; } try {//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 (': '); dc. ColumnName = strcell[0]. Replace ("\" "," "); Tb. Columns.Add (DC); } TB. AcceptChanges (); }//Add content DataRowDr = TB. NewRow (); for (int j = 0; J < Strrows.length; J + +) {Dr[j] = Strrows[j]. Split (': ') [1]. Replace ("\" "," "); } TB. Rows.Add (DR); Tb. AcceptChanges (); }} catch (Exception ee) {MessageBox.Show (EE. ToString ()); } return TB; } #endregion
Identify whether a string is in JSON format: http://www.php.cn/csharp-article-352536.html
The format is as follows:
{" table": [ { "Column1": 1, "Column2": 2, "Column3": 3 }, { "Column1": 1, " Column2 ": 2, " Column3 ": 3 } ]}
For example:
[{"Code": "MetaDataId", "name": "MetaDataId"},{"code": "Metadatacode", "name": "Number"},{"code": "SolutionName", "Name": " Name "}]
After formatting:
[ { "code": "MetaDataId", "Name": "MetaDataId" }, { "code": "Metadatacode", " Name ":" Number " }, { " code ":" SolutionName ", " name ":" Name " }]
Code formatter tool: Http://tool.oschina.net/codeformat/xml
Post-conversion effects are as follows:
The above is C # to parse Json into datetable content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!