ASP.Net MVC:如何根据原始的JSON数据创建一个JsonResult [英] ASP.Net MVC: how to create a JsonResult based on raw Json Data

查看:103
本文介绍了ASP.Net MVC:如何根据原始的JSON数据创建一个JsonResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个字符串包含以下原始JSON数据(简化问题的缘故):

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

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

我怎样才能创建一个 JsonResult 对象重新presenting MyString中

How can I create a JsonResult object representing MyString?

我试着使用JSON(对象)的方法。但它处理的原始JSON数据作为一个字符串-logically:P-。所以返回的HTTP响应如下:

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' }"

,而不是用给定的JSON数据:

instead of the given raw Json Data:

{ 'val': 'apple' }

这就是我想要达到什么的:

推荐答案

控制器 JSON()实际上是创建一个新的 JsonResult 一个辅助方法。如果我们看一下<一个href=\"http://aspnetwebstack.$c$cplex.com/SourceControl/changeset/view/85167bfa18b8#src/System.Web.Mvc/JsonResult.cs\">the来源$ C ​​$ C该类 * ,我们可以看到,它不是真的这样做了 - 内容类型只是设置为应用程序/ JSON ,序列化使用的JavaScriptSerializer 您的数据对象,写它生成的字符串。您可以复制这种行为(减去系列化,因为你已经做到这一点),通过返回 ContentResult类型从您的控制器来代替。

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");
}


* 在MVC2开始, JsonResult 还抛出一个异常,如果用户正在一个HTTP GET请求(而不是说POST) 。允许用户使用检索JSON的HTTP GET有安全隐患,你应该知道的你在你自己的应用程序允许在此之前。


* 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.

这篇关于ASP.Net MVC:如何根据原始的JSON数据创建一个JsonResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆