0

I need to Serialize\Deserialze between DataTable and json using json.net.

I found that json.net igrone the "TableName" Attribute.how can i add it?

code like this.

DataTable table = new DataTable();
table.TableName = "TestTable";
table.Columns.Add("id", typeof(int));
table.Columns.Add("name", typeof(string));
var dr = table.NewRow();
dr["id"] = 1;
dr["name"] = "foo";
table.Rows.Add(dr);

var json = JsonConvert.SerializeObject(table);
var o = JsonConvert.DeserializeObject<DataTable>(json);

when Serialize, got json [{"id":1,"name":"foo"}]. this json does not have TableName,and Deserialize it , the table also haven't TableName.

so,I need the TableName ,how can i hold it?

1
  • in the json.net sourcecode there are some code for read tablename,but i can;t find how to write it into json .if (reader.TokenType == JsonToken.PropertyName) { dt = new DataTable((string)reader.Value); reader.Read(); } else { dt = new DataTable(); } Commented Dec 25, 2012 at 1:41

1 Answer 1

2

I've created a custom DataTable converter for JSON.NET that does this. Grab the source from here: https://github.com/chris-herring/DataTableConverter

Use it like this:

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

It serializes/deserializes a System.Data.DataTable in this format:

{
    "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"]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.