我在EmployeeController中有以下示例代码,它创建了几个员工,将他们添加到员工列表中,然后在获取请求时返回员工列表。从代码返回的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结果
之所以会发生这种情况,是因为您实际返回的不是List<Employee>
,而是一个包含List<Employee>
的对象(EmployeeList)。
将其更改为返回Employee[]
(Employee的数组)或仅返回List<Employee>
而不返回其周围的类
您返回的不是列表,而是一个嵌入了列表的对象。将方法的签名更改为:
public List<Employee> Get()
然后只返回列表:
return empList.Employees;