简体   繁体   中英

Convert DataTable to nested json in c#

I want to convert datatable into nested json but get following error:

"An item with the same key has already been added."

Data

CstCmpCode       Main_Group      Sub_Group    ClosBal
 AH01            Neck Wraps        AFGHANI      7 

Now I want JSON result something like:

{
  "CstCmpCode": "AH01",
  "Main_Group": "Neck Wraps",
  "sub_group": [
    {
      "Sub_Group": "AFGHANI",
      "ClosBal": 7
    }
  ]
}

I used the following code:

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; }
}

In your code here:

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"]);
             ^^^^^^^

I assume the problem is here - you add to the sub dictionary the rs["Sub_Group"] without checking if it exists. So if you have the same Sum_Group twice for that Main_group value it will throw the exception you get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM