将数据表转换为c#中的嵌套json



我想把数据表转换成嵌套的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两次,它将抛出您得到的异常。

相关内容

  • 没有找到相关文章

最新更新