将数据表转换为嵌套json c时出现问题#

时间:2016-08-17 07:29:41

标签: c# json

我有一个SQL表,其值如:

 Main_group   Sub_group  CstCmpCode
 COMBO SET    DD-101       AH01
 COMBO SET    DD-102       AH01

我需要创建嵌套的json字符串,如:

{
  "CstCmpCode": "AH01",
  "Main_Group": "COMBO SET",
  "sub_group": [
      {
         "Sub_Group": "DD-101",
      },
      {
         "Sub_Group": "DD-102", 
      }
    ]
}

我的代码如下所示,用于将数据表转换为嵌套的json字符串:

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 distinct Main_group, Sub_group, CstCmpCode 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();

List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
    row = new Dictionary<string, object>();
    foreach (DataColumn col in dt.Columns)
    {
        row.Add(col.ColumnName, rs[col]);
    }
    rows.Add(row);
}  

PLS。检查上面我将会出错的地方。

感谢。
Yogesh.Sharma

2 个答案:

答案 0 :(得分:0)

该行:

row.Add(col.ColumnName, rs[col]);

在这里,您尝试将不同类型的对象添加到您的此集合中。如果所有值都可以存储为字符串(我想这没关系,因为您之后创建了JSon对象,请尝试将该行更改为:

 row.Add(col.ColumnName, rs[col].ToString());

答案 1 :(得分:0)

您似乎需要对Main_GroupCstCmpCode进行分组,我建议您简单Linq进行分组并选择所需格式并将其传递给JavaScriptSerializer以进行序列化

var results = dt.AsEnumerable()
    .GroupBy(x => 
        new
        {
            Main_group = x.Field<string>("Main_group"),
            CstCmpCode = x.Field<string>("CstCmpCode")
        })
    .Select(x=> 
        new
        {
            Main_group = x.Key.Main_group,
            CstCmpCode = x.Key.CstCmpCode,
            sub_group = x.Select(s => new {Sub_Group= s.Field<string>("Sub_group") })

        } );

JavaScriptSerializer serializer = new JavaScriptSerializer();
var serializedString = serializer.Serialize(results);

输出

[{
    "Main_group": "COMBO SET",
    "CstCmpCode": "AH01",
    "Sub_group": ["DD-101 ", "DD -102 "]
}]