I have the following sample code in an EmployeeController that creates a couple of employees, adds them to an employee list, and then returns the employee list on a get request. The returned JSON from the code includes Employees as a root node. I need to return a JSON array without the Employees property because whenever I try to parsethe JSON result to objects I get errors unless I manually reformat the string to not 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 I receive when the controller is called
{
"Employees":
[
{"EmployeeID":1,"Name":"John","Position":"CEO"},
{"EmployeeID":2,"Name":"Jason","Position":"CFO"}
]
}
This is the JSON result that I need returned
[
{"EmployeeID":1,"Name":"John","Position":"CEO"},
{"EmployeeID":2,"Name":"Jason","Position":"CFO"}
]
Any help is much appreciated as I am new to WEBAPI and parsing the JSON results
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
By removing application/xml you remove the ability for the Web API to return XML if the client requests that specifically. e.g. if you send "Accept: application/xml" you will still receive JSON.
That happens because you are not actually returning a List<Employee>
but an object (EmployeeList) that has a List<Employee>
in it.
Change that to return Employee[]
(an array of Employee) or a mere List<Employee>
without the class surrounding it
You're not returning a list but an object with embedded list in it. Change a signature of your method to:
public List<Employee> Get()
And then return only list:
return empList.Employees;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With