小编典典

WebAPI返回没有根节点的JSON数组

json

我在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结果


阅读 276

收藏
2020-07-27

共1个答案

小编典典

发生这种情况是因为您实际上没有返回a,List<Employee>而是返回其中包含a
的对象(EmployeeList)List<Employee>
将其更改为return Employee[](一组Employee)或仅List<Employee>包含类而没有返回

2020-07-27