I would like to return JSON from Web Api 2 controller. My current code does not work on Included properties. My get method is:
[System.Web.Mvc.HttpGet]
public IQueryable<Employee> GetEmployee()
{
return db.Employee.Include(x=>x.Department);
}
I've added this line to my WebApiConfig:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
On get I'm getting this error:
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
When I was using standard controller (not the Api one) my code was :
[HttpGet]
public ActionResult GetCountries()
{
var countries = JsonConvert.SerializeObject(db.Countries.Include(x => x.Regions), Formatting.None, new JsonSerializerSettings() {ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore });
return Content(countries, "application/json");
}
But Content() is specific for Controller class and I guess it cant be used in WebApi Controllers.
Desired JSON structure is:
[
{
"Iso3": "AL",
"CountryNameEnglish": "Alaska",
"Regions": [
{
"RegionCode": "AL1",
"Iso3": "AL",
"RegionNameEnglish": "Alaskan Region 1"
},
{
"RegionCode": "AL2",
"Iso3": "AL",
"RegionNameEnglish": "Alaskan Region 2"
}
]
}
]
Does anybody know how to handle this?