C # parse Json into DateTable,
# Region parses Json into DateTable /// <summary> /// parses Json into DateTable. /// Json Data Format: // {table: [{column1: 1, column2: 2, column3: 3}, {column1: 1, column2: 2, column3: 3}]} // </summary> // <param name = "strJson"> the Json string to be parsed </param> // <returns> returns DateTable </returns> public DataTable JsonToDataTable (string strJson) {// retrieve the table name var rg = new Regex (@"(? <= {) [^:] + (? =: \ [) ", RegexOptions. ignoreCase); string strName = rg. match (strJson ). value; DataTable tb = null; // if (strJson. trim (). length = 0) {return tb;} // check whether strJson is a json string if (! JsonSplit. isJson (strJson) {return tb;} try {// remove the 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 a table if (tb = null) {tb = new able (); 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 () ;}} catch (Exception ee) {MessageBox. show (ee. toString ();} return tb;} # endregion
Identify whether a string is in Json format: http://blog.csdn.net/jiankunking/article/details/42531209
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": "No "}, {"Code": "SolutionName", "Name": "Name"}]
After formatting:
[{"Code": "MetaDataId", "Name": "MetaDataId" },{ "Code": "MetadataCode", "Name": "No "}, {"Code": "SolutionName", "Name": "Name"}]
Code formatting tool: http://tool.oschina.net/codeformat/xml
The converted results are as follows:
Code Source: http://zhidao.baidu.com/link? Url = Qf5sRgBcmErNAAaquKuMZSesDtTLpqWzy61N3sBBV2n4sqdBX-X3Zn-e5EEWO8KmlkhzO8Tbkv31yUbYpwSh076QrXmCgHseCiMjkATl1rO