0

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?

1 Answer 1

1

I figured it out after a long while:

[System.Web.Mvc.HttpGet]
public IHttpActionResult GetEmployee()
{
    var employee= db.Employee.Include(x => x.Department);
    return Json(employee, new JsonSerializerSettings(){ReferenceLoopHandling = ReferenceLoopHandling.Ignore});

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.