在C#中使用嵌套数组反序列化JSON的问题

时间:2016-08-17 05:34:01

标签: c# json

  

"转换值时出错\" \ u0004 Primary \"键入\ u0027System.Collections.Generic.List`1 [WebService + SubGroup] \ u0027。 Path \ u0027 [0] .Sub_Group \ u0027,第1行,第68位。"

数据

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, 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();

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

      var json = serializer.Serialize(rows);

      var test = JsonConvert.DeserializeObject<List<RootObject>>(json, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });

课程如下:

public class RootObject
{
    public string CstCmpCode { get; set; }
    public string Main_Group { get; set; }
    public List<SubGroup> sub_group { get; set; }
}

 public class SubGroup
{
    public string Sub_Group { get; set; }
    public int ClosBal { get; set; }
}

0 个答案:

没有答案