将数据表转换为c#中的嵌套json
本文关键字:嵌套 json 数据表 转换 | 更新日期: 2023-09-27 18:02:37
我想把数据表转换成嵌套的json,但得到以下错误:
数据"已添加具有相同键的项。"
CstCmpCode Main_Group Sub_Group ClosBal
AH01 Neck Wraps AFGHANI 7
现在我想要JSON结果如下:
{
"CstCmpCode": "AH01",
"Main_Group": "Neck Wraps",
"sub_group": [
{
"Sub_Group": "AFGHANI",
"ClosBal": 7
}
]
}
我使用了以下代码:
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TallyWeb"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select CstCmpCode, Loaded_date, Main_Group, Sub_Group, ClosBal from TlyStkSumm where CstCmpCode = @CstCmpCode";
cmd.Parameters.AddWithValue("@CstCmpCode", CstCmpCode);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
var main = new Dictionary<string, Dictionary<string, string>>();
foreach (DataRow rs in dt.Rows)
{
string Main_Group = rs["Main_Group"].ToString();
Dictionary<string, string> sub;
if (!main.TryGetValue(Main_Group, out sub))
{
sub = new Dictionary<string, string>();
main.Add(Main_Group, sub);
}
sub.Add(rs["Sub_Group"].ToString(), (string)rs["ClosBal"]);
}
RootObject root = new RootObject { main = main };
public class RootObject
{
[JsonProperty("main")]
public Dictionary<string, Dictionary<string, string>> main { get; set; }
}
在您的代码中:
string Main_Group = rs["Main_Group"].ToString();
Dictionary<string, string> sub;
if (!main.TryGetValue(Main_Group, out sub))
{
sub = new Dictionary<string, string>();
main.Add(Main_Group, sub);
}
sub.Add(rs["Sub_Group"].ToString(), (string)rs["ClosBal"]);
^^^^^^^
我认为问题在这里-您将rs["Sub_Group"]
添加到sub
字典而不检查它是否存在。因此,如果您对Main_group
值有相同的Sum_Group
两次,它将抛出您得到的异常。