WebAPI Return JSON 没有根节点的数组
WebAPI Return JSON array without root node
我在 EmployeeController 中有以下示例代码,它创建了几个员工,将他们添加到员工列表中,然后 return 根据 get 请求发送员工列表。代码中的 returned JSON 包括 Employees 作为根节点。我需要 return 一个没有 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 结果 returned
[
{"EmployeeID":1,"Name":"John","Position":"CEO"},
{"EmployeeID":2,"Name":"Jason","Position":"CFO"}
]
非常感谢任何帮助,因为我是 WEBAPI 的新手并且正在解析 JSON 结果
发生这种情况是因为您实际上 return 并不是 List<Employee>
,而是一个包含 List<Employee>
的对象 (EmployeeList)。
将其更改为 return Employee[]
(员工数组)或仅 List<Employee>
周围没有 class
您不是在 return 列表,而是在其中嵌入列表的对象。将您的方法签名更改为:
public List<Employee> Get()
然后return只列出:
return empList.Employees;
我在 EmployeeController 中有以下示例代码,它创建了几个员工,将他们添加到员工列表中,然后 return 根据 get 请求发送员工列表。代码中的 returned JSON 包括 Employees 作为根节点。我需要 return 一个没有 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 结果 returned
[
{"EmployeeID":1,"Name":"John","Position":"CEO"},
{"EmployeeID":2,"Name":"Jason","Position":"CFO"}
]
非常感谢任何帮助,因为我是 WEBAPI 的新手并且正在解析 JSON 结果
发生这种情况是因为您实际上 return 并不是 List<Employee>
,而是一个包含 List<Employee>
的对象 (EmployeeList)。
将其更改为 return Employee[]
(员工数组)或仅 List<Employee>
周围没有 class
您不是在 return 列表,而是在其中嵌入列表的对象。将您的方法签名更改为:
public List<Employee> Get()
然后return只列出:
return empList.Employees;