Convert datatable to JSON in C#

后端 未结 17 1112
猫巷女王i
猫巷女王i 2020-11-22 11:53
  1. I want to get records from database into a DataTable.
  2. Then convert the DataTable into a JSON object.
  3. Return the JSON ob
17条回答
  •  清酒与你
    2020-11-22 12:37

    I am using this function for describe table.
    Use it after fill datatable

    static public string DataTableToJSON(DataTable dataTable,bool readableformat=true)
            {
                string JSONString="[";
                string JSONRow;
                string colVal;
                foreach(DataRow dataRow in dataTable.Rows)
                {
                    if(JSONString!="[") { JSONString += ","; }
                    JSONRow = "";
                    if (readableformat) { JSONRow += "\r\n"; }
                    JSONRow += "{";
    
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        colVal = dataRow[col].ToString();
                        colVal = colVal.Replace("\"", "\\\"");
                        colVal = colVal.Replace("'", "\\\'");
                        if(JSONRow!="{"&&JSONRow!="\r\n{") {
    
                            JSONRow += ",";
    
                        }
                        JSONRow += "\"" + col.ColumnName + "\":\"" + colVal + "\"";
    
                    }
                    JSONRow += "}";
                    JSONString += JSONRow;
                }
                JSONString += "\r\n]";
                return JSONString;
            }
    

    MySQL Query: "DESCRIBE TableName;"; DataTableToJSON(dataTable) Example Output:

    [
    {"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
    {"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
    {"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
    {"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
    {"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
    {"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
    ]
    

    Tested With PHP:

    $X='[
    {"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
    {"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
    {"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
    {"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
    {"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
    {"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
    ]';
    $Y=json_decode($X,true);
    echo $Y[0]["Field"];
    var_dump($Y);
    

提交回复
热议问题