日期:2014-05-18  浏览次数:20769 次

一个递归方法写法,求助
有这么一个对象,拥有众多属性,比如这个对象是Person拥有 姓名,年龄和一个List<Person>属性,现在要用将这样的一个对象集合写成一个Json,我老早就看到这歌问题,至今没写好,求帮助了呗.最后的结果,List<Person>作为Json的一个子节点存在如:
C# code

[
    { 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: '子集合为空的' }
]




来大神一起讨论盘呗

------解决方案--------------------
C# code
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);