C # parse Json into DateTable,
# Region parses Json into DateTable ///
/// Parse Json into DateTable.
/// Json Data Format :///
{Table: [{column1: 1, column2: 2, column3: 3}, {column1: 1, column2: 2, column3: 3}]}
///
/// Json string to be parsed
/// Return DateTable public DataTable JsonToDataTable (string strJson)
{
//
Retrieve the table name var rg = new Regex (@(? <= {) [^:] + (? =: [), RegexOptions. IgnoreCase );
String strName = rg. Match (strJson). Value; DataTable tb = null;
// Remove the table name strJson = strJson. Substring (strJson. IndexOf ([) + 1 );
StrJson = strJson. Substring (0, strJson. IndexOf (]);
// Obtain 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 a 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 DataRow dr = tb. NewRow ();
For (int j = 0; j <strRows. Length; j ++)
{Dr [j] = strRows [j]. Split (':') [1]. Replace (,
);
} Tb. Rows. Add (dr );
Tb. AcceptChanges ();
}
Return tb ;}
# Endregion
?
?
The format is as follows:
?
1234567891011121314 |
{ table: [ { column1: 1 , column2: 2 , column3: 3 }, { column1: 1 , column2: 2 , column3: 3 } ] } |
For example:
?
1 |
[{Code: MetaDataId, Name: MetaDataId}, {Code: MetadataCode, Name: No.}, {Code: SolutionName, Name: Name}] |
After formatting:
?
1234567891011121314 |
[ { Code: MetaDataId, Name: MetaDataId }, { Code: MetadataCode, Name: No. }, { Code: SolutionName, Name: Name } ] |