WebAPI返回没有根节点

时间:2015-11-30 20:35:11

标签: c# json json.net asp.net-web-api2

我在EmployeeController中有以下示例代码,它创建了几个员工,将它们添加到员工列表,然后在get请求中返回员工列表。代码中返回的JSON包括Employees作为根节点。我需要返回一个没有Employees属性的JSON数组,因为每当我尝试将JSON结果解析为对象时,我都会收到错误,除非我手动重新格式化字符串以使其不包含它。

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

这是我在调用控制器时收到的JSON结果

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

这是我需要返回的JSON结果

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

我非常感谢任何帮助,因为我是WEBAPI的新手并且正在解析JSON结果

2 个答案:

答案 0 :(得分:9)

这是因为您实际上并没有返回List<Employee>,而是返回一个List<Employee>的对象(EmployeeList)。
更改为返回Employee[](一个Employee数组)或仅仅List<Employee>没有围绕它的类

答案 1 :(得分:2)

您没有返回列表,而是返回包含嵌入列表的对象。将方法的签名更改为:

public List<Employee> Get()

然后只返回列表:

return empList.Employees;