Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

How can I create a JsonResult object representing MyString?

I tried to use the Json(object) method. but it handles the raw json data as an string -logically :P-. So the returned HTTP response looks like:

"{ 'val': 'apple' }"

instead of the given raw Json Data:

{ 'val': 'apple' }

this is what I want to achieve:

like image 810
SDReyes Avatar asked Oct 21 '10 20:10

SDReyes


1 Answers

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.

like image 54
Brant Bobby Avatar answered Sep 23 '22 22:09

Brant Bobby