【问题标题】:Achieve Json result to list实现Json结果列表
【发布时间】:2016-11-30 15:08:12
【问题描述】:
 public class Child
    {
        public int ids { get; set; }
        public string names { get; set; }

    }

    public class RootObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public int ids { get; set; }
        public string names { get; set; }
        public List<Child> children { get; set; }
    }
}

从上面我们如何实现我的 Json 渲染的结果

[
        {
            id: 1,
            names: 'root1',
            children: [
                { id: 2, name: 'child1' },
                { id: 3, name: 'child2' }
            ]
        },

    ];

我的局部变量创建一个实例。 发生了什么,应用程序连接到一个文件夹。取决于它循环通过多少个文件。 问题是我无法正确返回儿童的上述结构。有点卡住,知道我错过了一些小东西。 任何人都可以举例来实现这些结果,而不是链接到网站。

var attachmentsList = new List<RootObject>();
FileInfo[] files = dinfo.GetFiles();

                foreach (FileInfo file in files)
                {

                    attachmentsList.Add(new RootObject
                    {
                        id = i + 1,
                        name = "Folder" + i + 1,
                        children = new List<Child>(
                            id = i + 1,
                            file.Name
                        )

                    });
 i++;
}

【问题讨论】:

    标签: c# asp.net .net json


    【解决方案1】:

    您需要遍历每个选定目录中的文件:

    var attachmentsList = new List<RootObject>();
    
    FileInfo[] files = dinfo.GetFiles();
    var rootObject = new RootObject {  
                                        id = 1, 
                                        name = "Folder1", 
                                        children = new List<Child>()
                                    };
    
    foreach (FileInfo file in files)
    {
          rootObject.children.Add(new Child { id = i + 1, file.Name });
          i++;
    }
    
    attachmentsList.Add(rootObject);
    

    【讨论】:

    • 好的,但是 id 说 child 不包含 id 的定义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多