【问题标题】:ASP.Net : DataTable convert to JSON with HierarchyASP.Net:DataTable 使用层次结构转换为 JSON
【发布时间】:2014-06-25 05:10:37
【问题描述】:

您好,我在将 dataTable 转换为 JSON 格式时遇到问题,但我无法获得所需的输出。

这里是数据表的例子

 Parent        Child
   P1           c1
   P1           c2
   P1           c3
   P2           c4

我需要的输出是:

 [{
    Parent:P1,
    Child:[
            {c1},
            {c2},
            {c3}
           ]
 },
 {
    Parent:P2
    Child:[{c4}]
 }] 

但我总是得到的输出是:

    [{Parent:P1, Child:c1}, {Parent:P1, Child:c2}, {Parent:P1, Child:c3}, {Parent:P2,
           Child:c4}]

【问题讨论】:

标签: c# jquery asp.net json datatable


【解决方案1】:

使用以下代码获得您想要的结果。

public class ParentNode
{
    public ParentNode()
    {
        this.Child = new List<ChildNode>();
    }
    public string Parent { get; set; }
    public List<ChildNode> Child { get; set; }
}

public class ChildNode
{
    public string Child { get; set; }
}

class DataTableTOJSON
{   
    public static string GetJSON(DataTable dt)
    {            
        List<ParentNode> parent = new List<ParentNode>();            

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            var innerRow = dt.Rows[i]["Parent"];
            var objParent = new ParentNode();
            bool alreadyExists = parent.Any(x => x.Parent.Contains(innerRow.ToString()));

            if (alreadyExists)
                continue;

            DataRow[] foundRows = dt.Select("[Parent]='" + innerRow + "'");

            for (int k = 0; k < foundRows.Count(); k++)
            {
                var objChild = new ChildNode();
                objChild.Child = foundRows[k]["Child"].ToString();
                objParent.Child.Add(objChild);
            }

            objParent.Parent = innerRow.ToString();
            parent.Add(objParent);
        }
        JavaScriptSerializer jsonString = new JavaScriptSerializer();
        return jsonString.Serialize(parent);
    }
}

您将获得以下输出。

[{"父":"P1","子":[{"子":"c1"},{"子":"c2"},{"子":"c3"}]}, {"父":"P2","子":[{"子":"c4"}]}]

希望对你有帮助。

【讨论】:

  • 嗨,Nitesh,我无法使用“var”类型变量,因为我正在为这个项目使用 .net 2.0。我也不能使用 linq 类型代码。请帮我解决这个问题。提前谢谢你...
猜你喜欢
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 2021-04-04
  • 2021-07-15
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多