简体   繁体   中英

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?

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

The MVC Controller class has a Json method which is used to convert an object into a JsonResult . You do not need to manually serialize the object using JavaScriptSerializer . Just pass the object to the Json method, and it will be serialized for you when the result is executed. If your controller method is a GET method, then you will also need to pass JsonRequestBehavior.AllowGet as the second parameter of the Json method, otherwise it will throw an error.

[HttpGet]
public ActionResult GetMyList()
{
    List<object> list = getList();
    return Json(list, JsonRequestBehavior.AllowGet);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM