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(集合)的方式,这样一来可以不用在前端再去处理

asp.net mvc 对象和集合序列化,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。