C# 从数据集生成JSON
我正在使用ExtJS生成一棵树。它需要以下格式的JSON:C# 从数据集生成JSON,c#,json,extjs4,C#,Json,Extjs4,我正在使用ExtJS生成一棵树。它需要以下格式的JSON: { "children": [{ "text": "Invisible", "expanded": true, "children": [{ "text": "Billing", "leaf": true }, { "text": "Sales", "leaf": true
{ "children": [{
"text": "Invisible",
"expanded": true,
"children": [{
"text": "Billing",
"leaf": true
}, {
"text": "Sales",
"leaf": true
}]
},
{
"text": "Visible",
"expanded": true,
"children": [{
"text": "Equipment",
"leaf": true
}, {
"text": "Process",
"leaf": true
}]
}]
}
我在数据集中得到的结果是:
textvisibleleafexpanded
Billing0truefalse
销售是假的
设备1真假
Process1truefalse
visible='1'的所有记录都应在'visible'节点下生成,visible='0'的所有记录都应在'Invisible'节点下生成。我只是无法生成JSON。如何以上述格式生成它?我创建了一个类,如下所示:
public class TreeNode
{
public string text { get; set; }
public bool leaf { get; set; }
public bool expanded { get; set; }
public List<TreeNode> children { get; set; }
public TreeNode()
{
leaf = false;
expanded = true;
children = new List<TreeNode>();
}
}
List<TreeNode> treeNodeList = new List<TreeNode>();
treeNodeList.Add(new TreeNode
{
text = "Invisible",
expanded = true,
leaf = false
});
treeNodeList.Add(new TreeNode
{
text = "Visible",
expanded = true,
leaf = false
});
if (ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
treeNodeList[0].children.Add(new TreeNode
{
text = ds.Tables[0].Rows[i][0].ToString(),
leaf = true
});
}
}
if (ds.Tables.Count > 1)
{
for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
{
treeNodeList[1].children.Add(new TreeNode
{
text = ds.Tables[1].Rows[i][0].ToString(),
leaf = true
});
}
}
return treeNodeList;
根据返回的数据集,我创建了如下对象:
public class TreeNode
{
public string text { get; set; }
public bool leaf { get; set; }
public bool expanded { get; set; }
public List<TreeNode> children { get; set; }
public TreeNode()
{
leaf = false;
expanded = true;
children = new List<TreeNode>();
}
}
List<TreeNode> treeNodeList = new List<TreeNode>();
treeNodeList.Add(new TreeNode
{
text = "Invisible",
expanded = true,
leaf = false
});
treeNodeList.Add(new TreeNode
{
text = "Visible",
expanded = true,
leaf = false
});
if (ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
treeNodeList[0].children.Add(new TreeNode
{
text = ds.Tables[0].Rows[i][0].ToString(),
leaf = true
});
}
}
if (ds.Tables.Count > 1)
{
for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
{
treeNodeList[1].children.Add(new TreeNode
{
text = ds.Tables[1].Rows[i][0].ToString(),
leaf = true
});
}
}
return treeNodeList;
到目前为止你有什么?看看linq,谢谢。我用它来创建一个复杂的类型。如果有人需要,我会发布解决方案。