ASP.Net MVC: how to create a JsonResult based on raw Json Data

前端 未结 3 1408
有刺的猬
有刺的猬 2020-12-16 19:29

Having a string containing the following raw Json data (simplified for the sake of the question):

  var MyString =  \"{ \'val\': \'apple\' }\";
         


        
相关标签:
3条回答
  • 2020-12-16 19:44

    I think you can use the JavaScriptSerializer class for this

    var js = new System.Web.Script.Serialization.JavaScriptSerializer();
    var jsonObject = js.Deserialize("{ 'val': 'apple' }", typeof(object));
    
    0 讨论(0)
  • 2020-12-16 19:45

    The Json() method on Controller is actually a helper method that creates a new JsonResult. If we look at the source code for this class*, we can see that it's not really doing that much -- just setting the content type to application/json, serializing your data object using a JavaScriptSerializer, and writing it the resulting string.. You can duplicate this behavior (minus the serialization, since you've already done that) by returning a ContentResult from your controller instead.

    public ActionResult JsonData(int id) {
        var jsonStringFromSomewhere = "{ 'val': 'apple' }";
        // Content() creates a ContentResult just as Json() creates a JsonResult
        return Content(jsonStringFromSomewhere, "application/json");
    }
    

    * Starting in MVC2, JsonResult also throws an exception if the user is making an HTTP GET request (as opposed to say a POST). Allowing users to retrieve JSON using an HTTP GET has security implications which you should be aware of before you permit this in your own app.

    0 讨论(0)
  • 2020-12-16 19:45

    The way I have generated json data from a string is by using JavaScriptResult in the controller:

    public JavaScriptResult jsonList( string jsonString)
    {
       jsonString = "var jsonobject = new Array(" + jsonString + ");";
       return JavaScript(jsonString)
    }
    

    Then when you request pass the json string to that action in your controller, the result will be a file with javascript headers.

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