您可以使用 LINQ 和Json.NET。在您的班级顶部添加:
using System.Linq;
在您的代码中,您可能有两种方法:
// 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());
}
}