LINQ とJson.NETを使用できます。クラスの一番上に次を追加します。
using System.Linq;
コードには、次の 2 つのアプローチがある場合があります。
// 1. select the row in the table
// 2. create an anonymous object
// 3. serialize it
var json1 = JsonConvert.SerializeObject(table.Select("ID=12")
.Select(row => new
{
id = row["ID"],
name = row["Name"],
add = row["Add"],
edit = row["Edit"],
view = row["View"],
authorize = row["Authorize"]
}).FirstOrDefault());
// 1. cast all rows in the table
// 2. create a collection of anonymous objects
// 3. select the anonymous object by id
// 4. serialize it
var json2 = JsonConvert.SerializeObject(table .Rows
.Cast<DataRow>()
.Select(row => new
{
id = row["ID"],
name = row["Name"],
add = row["Add"],
edit = row["Edit"],
view = row["View"],
authorize = row["Authorize"]
})
.FirstOrDefault(row => row.id.ToString() == "12"));
または、独自のクラスを使用することもできます。このオプションは必ずしも LINQ を必要としません。
// 1. select the row
// 2. create a new TableRow object
// 3. serialize it
var filteredRow = table.Select("ID=12");
if (filteredRow.Length == 1)
{
var json3 = JsonConvert.SerializeObject(
new TableRow(filteredRow[0].ItemArray));
}
簡略化されTableRow
たクラス定義は次のようになります。
public class TableRow
{
public int id { get; set; }
public string name { get; set; }
public bool add { get; set; }
public bool edit { get; set; }
public bool view { get; set; }
public bool authorize { get; set; }
public TableRow(object[] itemArray)
{
id = Int32.Parse(itemArray[0].ToString());
name = itemArray[1].ToString();
add = bool.Parse(itemArray[2].ToString());
edit = bool.Parse(itemArray[3].ToString());
view = bool.Parse(itemArray[4].ToString());
authorize = bool.Parse(itemArray[5].ToString());
}
}