Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c# - WebAPI Return JSON array without root node

I have the following sample code in an EmployeeController that creates a couple of employees, adds them to an employee list, and then returns the employee list on a get request. The returned JSON from the code includes Employees as a root node. I need to return a JSON array without the Employees property because whenever I try to parsethe JSON result to objects I get errors unless I manually reformat the string to not include it.

public class Employee
{
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
}

public class EmployeeList
{
    public EmployeeList()
    {
        Employees = new List<Employee>();
    }
    public List<Employee> Employees { get; set; }
}


public class EmployeeController : ApiController
{
    public EmployeeList Get()
    {
        EmployeeList empList = new EmployeeList();
        Employee e1 = new Employee
        {
            EmployeeID = 1,
            Name = "John",
            Position = "CEO"
        };
        empList.Employees.Add(e1);
        Employee e2 = new Employee
        {
            EmployeeID = 2,
            Name = "Jason",
            Position = "CFO"
        };
        empList.Employees.Add(e2);

        return empList;
    }
}

This is the JSON result I receive when the controller is called

{
    "Employees":
        [
           {"EmployeeID":1,"Name":"John","Position":"CEO"},     
           {"EmployeeID":2,"Name":"Jason","Position":"CFO"}
        ]
}

This is the JSON result that I need returned

[
    {"EmployeeID":1,"Name":"John","Position":"CEO"},     
    {"EmployeeID":2,"Name":"Jason","Position":"CFO"}
]

Any help is much appreciated as I am new to WEBAPI and parsing the JSON results

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That happens because you are not actually returning a List<Employee> but an object (EmployeeList) that has a List<Employee> in it.
Change that to return Employee[] (an array of Employee) or a mere List<Employee> without the class surrounding it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...