asp.net mvc 对象和集合序列化

private List<Model.Organization.Organization> GetOrganiztions()
{
var organizations = new List<Model.Organization.Organization>();

organizations.Add(new Model.Organization.Organization
{
Id = "1",
Name = "一汽",
});

organizations.Add(new Model.Organization.Organization
{
Id = "2",
Name = "红旗",
ParentId = "1"
});
organizations.Add(new Model.Organization.Organization
{
Id = "3",
Name = "奔腾",
ParentId = "1"
});
organizations.Add(new Model.Organization.Organization 
{
Id="4",
Name="奔腾B70",
ParentId="3"
});
return organizations;
}

private void AttachChildren(TreeModel tree, List<Model.Organization.Organization> organizations)
{
if (Equals(tree, null))
{
return;
}

var organizationsTmp = organizations.Where(p => !string.IsNullOrEmpty(p.ParentId) && p.ParentId.Equals(tree.id)).ToList();
foreach (Model.Organization.Organization node in organizationsTmp)
{
var t = new TreeModel() { 
id=node.Id,
text=node.Name
};
tree.children.Add(t);
this.AttachChildren(t, organizations);
}
}

public IList<TreeModel> GetTree()
{
var organizations = this.GetOrganiztions();
var rootNode = organizations.Find(p => string.IsNullOrEmpty(p.ParentId));
var tree = new TreeModel()
{
id = rootNode.Id,
text = rootNode.Name
};

this.AttachChildren(tree, organizations);
return new List<TreeModel>() { tree };
}

如果GetTree返回的是集合,则Controler调用GetTree序列化为json以后为:

[{"id":"1","text":"一汽","children":[{"id":"2","text":"红旗","children":[]},{"id":"3","text":"奔腾","children":[{"id":"4","text":"奔腾B70","children":[]}]}]}]

如果GetTree返回的是对象,则Controler调用GetTree序列化为json以后为:

{"id":"1","text":"一汽","children":[{"id":"2","text":"红旗","children":[]},{"id":"3","text":"奔腾","children":[{"id":"4","text":"奔腾B70","children":[]}]}]}
在asp.net mvc中前端我们可能会经常用到json数组,我们可以考虑使用Json(集合)的方式,这样一来可以不用在前端再去处理
上一篇:Launcher知识的demo,手机管家小伙家与悬浮窗


下一篇:C#中将ListView数据导出为excel(转载)