猿问

序列化具有空数据表的 DataSet 会丢失所有列信息

我尝试将数据集序列化为 json。一切正常,但如果没有记录,则缺少列信息。我找到了一些解决方案,但没有一个不能解决我的问题。


我编写了一个存储过程来从 MSSQL 服务器检索所有表记录并将其存储到数据集中,然后尝试使用 NewtonSoft 序列化为 json,然后将其写入 Json 文件。


DataSet ds_v 

string json = JsonConvert.SerializeObject(ds_v);

System.IO.File.WriteAllText(Server.MapPath("~") + "/txt.json", json);

我想要如下的输出


{

"Table": [],//here iam getting empty table without having column informations.So i want to get the column informations



"Table1": [

{

 }]


}


翻过高山走不出你
浏览 94回答 1
1回答

守着星空守着你

您可以检查数据表的行数是否为 0,然后添加一个空行。然后您可以看到序列化后表的架构。像这样:if (ds_v.Tables[0].Rows.Count == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var row = ds_v.Tables[0].NewRow();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ds_v.Tables[0].Rows.Add(row);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }string json = JsonConvert.SerializeObject(ds_v);或者,如果您只想查看架构而不对数据集进行任何修改,您可以使用此代码var cols = ds_v.Tables[0].Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToList();var json = JsonConvert.SerializeObject(cols, Formatting.Indented);
随时随地看视频慕课网APP
我要回答