Search code examples
javascriptc#jsonasp.net-mvcjsonresult

How do I convert a List<object> to a JsonResult?


I'm trying to take a List of objects and return them as a JsonResult to an AJAX call. I'm trying this:

List<object> list = getList();
JavaScriptSerializer jss = new JavaScriptSerializer();
JsonResult json = jss.Serialize(list);

jss.Serialize takes an object as its parameter, so this is obviously not working. Is there a way I can just pass in a List of objects and get what I need returned?


Solution

  • The following example shows how to return an instance of the JsonResult class from an action method. The object that is returned specifies that a GET request is permitted.

     public ActionResult Movies()
     {
         var movies = new List<object>();
    
         movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984 );
         movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 );
         movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 });
    
         return Json(movies, JsonRequestBehavior.AllowGet);
     }
    

    Source : https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult(v=vs.118).aspx