0

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

code

 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);
        }

1 Answer 1

0

The second parameter for Json method in Web API controller is incorrectly assigned, since ApiController Json method requires JsonSerializerSettings as second argument:

protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings)
{
    ......
}

The MVC controller counterpart for Json method is shown below:

protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
   ......
}

In this case, if the controller class containing Get method above extends ApiController, you need to change 2 return Json statements to return new JsonResult as given below:

public class ControllerName : ApiController
{
    public JsonResult Get()
    {
        try
        {
            using (smartpondEntities DB = new smartpondEntities())
            {
                var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();

                // return JsonResult here
                return new JsonResult()
                {
                    Data = new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate }},
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }
        catch (Exception Ex)
        {
        }

        // return JsonResult here
        return new JsonResult()
        {
            Data = new { success = false },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

If you want to use MVC controller when returning JSON instead, change ApiController to Controller class from System.Web.Mvc namespace and keep return Json(...) there.

Similar issue:

JSON return error with ASP

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.