dotnetcoder dotnetcoder - 1 year ago 186
JSON Question

while using JsonRequestBehavior in web api giving error saying cannot convert to json.serializer

I am getting the following compilation error:

cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'


code

public class PondController : ApiController
{
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}

Answer Source

You are trying to use code snippet from ASP.NET MVC in ASP.NET WebAPI controller. In WebAPI the results and methods have different signatures. Try following:

public JsonResult<object> Get()
{
    try
    {
        using (smartpondEntities DB = new smartpondEntities())
        {
            var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
            return Json((object)new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } });
        }
    }
    catch (Exception Ex)
    {
    }
    return Json((object)new { success = false });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download