Return JSON using C# like PHP json_encode

前端 未结 4 790
醉酒成梦
醉酒成梦 2020-12-18 03:43

In PHP to return some JSON I would do:

return json_encode(array(\'param1\'=>\'data1\',\'param2\'=>\'data2\'));

how do I do the equivalent

相关标签:
4条回答
  • 2020-12-18 04:01

    You could use the JavaScriptSerializer class which is built-in the framework. For example:

    var serializer = new JavaScriptSerializer();
    string json = serializer.Serialize(new { param1 = "data1", param2 = "data2" });
    

    yields:

    {"param1":"data1","param2":"data2"}
    

    But since you talked about returning JSON in ASP.NET MVC 3 there are already built-in techniques that allow you to directly return objects and have the underlying infrastructure take care of serializing this object into JSON to avoid polluting your code with such plumbing.

    For example in ASP.NET MVC 3 you simply write a controller action returning a JsonResult:

    public ActionResult Foo()
    {
        // it's an anonymous object but you could have used just any
        // view model as you like
        var model = new { param1 = "data1", param2 = "data2" };
        return Json(model, JsonRequestBehavior.AllowGet);
    }
    

    You no longer need to worry about plumbing. In ASP.NET MVC you have controller actions that return action results and you pass view models to those action results. In the case of JsonResult it's the underlying infrastructure that will take care of serializing the view model you passed to a JSON string and in addition to that properly set the Content-Type response header to application/json.

    0 讨论(0)
  • 2020-12-18 04:03

    The simplest way it may be like this:

    public JsonResult GetData()
    {      
        var myList = new List<MyType>();
    
        //populate the list
    
        return Json(myList);
    }
    
    0 讨论(0)
  • 2020-12-18 04:08

    I always use JSON .Net: http://json.codeplex.com/ and the documentation: http://james.newtonking.com/projects/json/help/

    0 讨论(0)
  • 2020-12-18 04:15

    What about http://www.json.org/ (see C# list) ?

    0 讨论(0)
提交回复
热议问题