在此处的几篇文章中,在其他论坛上,我发现此代码将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());
"容器"必须是JArray
。
下次您有类似的问题,如@DR所建议。狡猾的,只需尝试序列化某些东西:
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"}]