WebAPI Return JSON array without root node

怎甘沉沦 提交于 2019-11-28 07:47:34

问题


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


回答1:


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




回答2:


You're not returning a list but an object with embedded list in it. Change a signature of your method to:

public List<Employee> Get()

And then return only list:

return empList.Employees;


来源:https://stackoverflow.com/questions/34007512/webapi-return-json-array-without-root-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!