在这里和其他论坛上的一些帖子中,我发现以下代码引用了将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)));
我做错什么了?
最佳答案
使用类似:
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"}]