日期:2014-05-18 浏览次数:20769 次
[ { name: '子集合不为空的', children: [ { name : '节点1.1' }, { name: '节点1.2' }, { name: '节点1.3', children: [ { name: '节点1.3.1' ,children: [ { name: '节点1.3.1.1' }, { name: '节点1.3.1.2' }] }, { name: '节点1.3.2' } ] }, { name: '节点1.4' } ] }, { name: '子集合为空的' }, { name: '子集合为空的' }, { name: '子集合为空的' } ]
class Person { public string name; public int age; public List<Person> children; public override string ToString() { StringBuilder builder = new StringBuilder(100); builder.Append("{ "); builder.Append("\"name\": \""); builder.Append(this.name); builder.Append("\", \"age\": \""); builder.Append(this.age); builder.Append("\""); if (this.children != null) { builder.Append(", \"children\": "); builder.Append(ListToStr(this.children)); } builder.Append(" }"); return builder.ToString(); } public static string ListToStr(List<Person> children) { StringBuilder builder = new StringBuilder(100); builder.Append("["); foreach (var item in children) { builder.Append(" "); builder.Append(item.ToString()); builder.Append(","); } builder.Remove(builder.Length - 1, 1); builder.Append(" ]"); return builder.ToString(); } } //调用 Person per = ... string str = per.ToString(); List<Person> list = ... string strlist = Person.ListToStr(list);