From DataTable in C# .NET to JSON

前端 未结 7 668
一整个雨季
一整个雨季 2020-12-04 18:12

I am pretty new at C# and .NET, but I\'ve made this code to call a stored procedure, and I then want to take the returned DataTable and convert it to JSON.

         


        
7条回答
  •  没有蜡笔的小新
    2020-12-04 19:11

    You could use the JSON.NET library: http://json.codeplex.com/ to serialize/deserialize the DataTable.

    string json = JsonConvert.SerializeObject(table);
    

    which serializes to something like this:

    [ { "Column1": "Row Value", "Column2": "2" } ]
    

    If you need to serialize more info about the DataTable e.g. column schema, primary key, table name then you could use the custom converter I wrote: https://github.com/chris-herring/DataTableConverter. Use it like this:

    string json = JsonConvert.SerializeObject(table, new Serialization.DataTableConverter());
    DataTable table = JsonConvert.DeserializeObject(json, new Serialization.DataTableConverter());
    

    which serializes to something like this:

    {
        "TableName": "TestTable",
        "Columns": [
            {
                "AllowDBNull": false,
                "AutoIncrement": true,
                "AutoIncrementSeed": 2,
                "AutoIncrementStep": 1,
                "Caption": "PrimaryKey",
                "ColumnName": "PrimaryKey",
                "DataType": "Int32",
                "DateTimeMode": "UnspecifiedLocal",
                "DefaultValue": null,
                "MaxLength": -1,
                "Ordinal": 0,
                "ReadOnly": false,
                "Unique": true
            }
        ],
        "Rows": [
            [
                1
            ],
            [
                2
            ],
            [
                3
            ]
        ],
        "PrimaryKey": ["PrimaryKey"]
    }
    

提交回复
热议问题