この関数を記述テーブルに使用しています。
データテーブルを埋めた後に使用します
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クエリ: "DESCRIBE TableName;"; DataTableToJSON(dataTable)出力例:
[
{"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":""}
]
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);