-1

我在我的应用程序中创建了一个数据表

DataTable table = new DataTable();

它具有以下格式

    ID    |  Name     |  Add    |   Edit  | View   | Authorize
    ---------------------------------------------------------------------
    10    | User      | true    |  trues  | trues  |  true
    11    | Group     | true    |  trues  | trues  |  true
    12    | Permission| true    |  trues  | trues  |  true

我想通过 id 从这个数据表中检索一行。

例如我想用id = 12

那是,

  12    | Permission| true    |  trues  | trues  |  true

之后,我只想使用 json.net 将此行转换为 json 字符串

{["id":"12","name":"Permission","add":true,"edit":true,"authorize":true,"view":true}]

可能吗?请帮忙

4

2 回答 2

2

您可以使用 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());
    }
}
于 2013-10-24T08:37:07.570 回答
0

如何使用Select方法DataTable

DataRow[] dr = table.Select("id = 12");

或者是动态的

int rowid = ... //assign some value through code and then
DataRow[] dr = table.Select("id = " + rowid);

我不知道 JSON 但你可以看看

使用每行键将 DataTable 转换为 JSON
http://www.codeproject.com/Tips/624888/Converting-DataTable-to-JSON-Format-in-Csharp-and
C# DataTable to Json?

于 2013-10-24T08:27:48.087 回答