user2543190 user2543190 - 4 days ago 6
ASP.NET (C#) Question

Achieve Json result to list

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; }
}
}


From above how we can achieve the result for my Json to render

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

];


my Local variable creating an instance.
What is going on, the application connection to a folder. depending on how many files it loops through.
The problem is I cannot return the above structure in children correctly. kind of stuck and know I am missing something small.
Can anyone make example to achieve these result, not link to websites.

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++;
}

Answer

You need to iterate over the files in each selected directory :

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);
Comments