将Json对象转换为DataTable

时间:2015-05-09 16:39:18

标签: c# datatable json.net deserialization json-deserialization

在这里以及其他论坛的一些帖子中,我发现这段代码用于将Json对象转换为DataTable:

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));  

我无法让这个工作。它总是抛出JsonSerializationException。我错过了什么吗?

这是显示错误的简单示例:

JObject query = new JObject();
JObject results = new JObject();

results.Add("Name", "Blue Umbrella");
results.Add("Price", 100);

query.Add("results", results);

DataTable dt = (DataTable)JsonConvert.DeserializeObject(query.ToString(), (typeof(DataTable)));

我做错了什么?

1 个答案:

答案 0 :(得分:7)

使用类似:

JArray array = new JArray();

{
    JObject row = new JObject();

    row.Add("Name", "Blue Umbrella");
    row.Add("Price", 100);

    array.Add(row);
}

{
    JObject row = new JObject();

    row.Add("Name", "Green Umbrella");
    row.Add("Price", 200);

    array.Add(row);
}

DataTable dt = JsonConvert.DeserializeObject<DataTable>(array.ToString());

“容器”必须是JArray

下次遇到类似问题时,正如@Dr所建议的那样。 Wily,只需尝试序列化一些东西:

var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");

var row = dt.NewRow();
row["Name"] = "Blue Umbrella";
row["Price"] = 100;
dt.Rows.Add(row);

row = dt.NewRow();
row["Name"] = "Green Umbrella";
row["Price"] = 200;
dt.Rows.Add(row);

string serialized = JsonConvert.SerializeObject(dt);

并查看其格式:

[{"Name":"Blue Umbrella","Price":"100"},{"Name":"Green Umbrella","Price":"200"}]