有一个 string
包含以下原始 Json 数据(为了问题而简化):
var MyString = "{ 'val': 'apple' }";
如何创建
JsonResult
对象表示 MyString
?我尝试使用 Json(object) 方法。但它将原始 json 数据作为字符串处理 - 逻辑上:P-。因此返回的 HTTP 响应如下所示:
"{ 'val': 'apple' }"
而不是给定的原始 Json 数据:
{ 'val': 'apple' }
这就是我想要实现的目标:
最佳答案
Json()
方法在 Controller
实际上是创建新 JsonResult
的辅助方法.如果我们看 the source code for this class *,我们可以看到它并没有真正做那么多——只是将内容类型设置为 application/json
,使用 JavaScriptSerializer
序列化您的数据对象,并将结果字符串写入它。您可以通过返回 ContentResult
来复制此行为(减去序列化,因为您已经这样做了)而是来自您的 Controller 。
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),也会抛出异常。允许用户使用 HTTP GET 检索 JSON 有 security implications在您自己的应用程序中允许这样做之前,您应该了解这一点。
关于asp.net-mvc - ASP.NET MVC : how to create a JsonResult based on raw Json Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3991751/