[英]ASP.Net : DataTable convert to JSON with Hierarchy
嗨,我在将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}]
使用以下代码可获得所需的结果。
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);
}
}
您将获得以下输出。
[{“ Parent”:“ P1”,“ Child”:[{“ Child”:“ c1”},{“ Child”:“ c2”},{“ Child”:“ c3”}]}},{“父母“:” P2“,” Child“:[{” Child“:” c4“}]}]]
我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.