正在将 Json 个对象转换为 DataTable

Converting Json object to DataTable

在这里和其他论坛的一些帖子中,我发现引用了这段代码,用于将 Json 对象转换为数据表:

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)));

我做错了什么?

使用类似于:

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());

"container" 必须是 JArray

下次遇到类似问题时,按照@Dr 的建议。 Wily's,简单地尝试序列化一些东西:

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"}]