WebAPI returns a JSON array without root node

I have the following code example in EmployeeController that creates a pair of employees, adds them to the list of employees, and then returns the list of employees in the receive request. The returned JSON from the code includes Employees as the root of the node. I need to return a JSON array without the Employees property, because whenever I try to parse the JSON result for objects, I get errors if I do not manually reformat the string so as not to 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 that I get when I call the controller

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

This is the JSON result I need to return

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

Any help is greatly appreciated as I am new to WEBAPI and analyzing JSON results.

+5
source share
2 answers

This is because you are not actually returning a List<Employee> , but an object (EmployeeList) in which there is a List<Employee> .
Change this to return Employee[] (array of Employee) or just List<Employee> without the class surrounding it

+8
source

You are not returning a list, but an object with a built-in list. Change the signature of your method to:

 public List<Employee> Get() 

And then return only the list:

 return empList.Employees; 
+2
source

Source: https://habr.com/ru/post/1237131/


All Articles