2016-09-20 52 views
0

由于种种原因,我从ASP.NET MVC 的内置JSON序列(即返回低于System.Web.Mvc.JsonResult对象(见编辑的一个交换))到Newtonsoft。直到我开始测试前,我才意识到前者返回JavaScript对象字面值,而Newtonsoft返回JSON格式的字符串返回JavaScript对象字面,没有JSON字符串,从ASP.NET MVC端点

我喜欢不必在客户端解析JSON字符串 - 它已经作为一个对象字面很方便 - 但我想坚持使用Newtonsoft出于其他技术原因。

例如,而不是看到我的客户对这个结果......

"{"Errors":["Please enter a valid email address."],"HasErrors":true}" 

...我希望看到这样的结果:

{"Errors":["Please enter a valid email address."],"HasErrors":true} // no quotes 

有没有一种方法,使Newtonsoft返回JS对象文字而不是字符串?

编辑

我的问题被陷害的方式并不是最好的。 JsonResult类型没有问题。事实上,解决方案仍然使用它。唯一的问题是默认的Controller.Json方法,它可以被覆盖以使用Newtonsoft(Json.NET)而不是内置的序列化程序。

+0

我不熟悉.NET世界 - 是服务器上的Newtonsoft吗?因为如果是这样,你永远不能从服务器返回一个JS文字。无论如何,都不在网络请求中。或者当它呈现时嵌入页面的某个地方? – vlaz

+0

你不能用JSON.Parse(响应)编辑你的JS文件吗? –

+1

你是如何创建你的JSON响应并使用Json.Net从MVC返回它们的? –

回答

1

只要写一个使用Newtonsoft串行定制JsonResult:

沿着东西线:

public abstract class BaseController : Controller 
{ 
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding) 
    { 
     return new JsonNetResult 
     { 
      ContentType = contentType, 
      ContentEncoding = contentEncoding, 
      Data = data 
     }; 
    } 

    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior) 
    { 
     return new JsonNetResult 
        { 
         ContentType = contentType, 
         ContentEncoding = contentEncoding, 
         Data = data, 
         JsonRequestBehavior = behavior 
        }; 
    } 
} 

JsonNetResult.cs:

using System; 
using System.Web; 
using System.Web.Mvc; 
using Newtonsoft.Json; 

public class JsonNetResult : JsonResult 
{ 
    public JsonSerializerSettings SerializerSettings { get; set; } 
    public Formatting Formatting { get; set; } 

    public JsonNetResult() 
    { 
     Formatting = Formatting.None; 
     SerializerSettings = new JsonSerializerSettings(); 
     JsonRequestBehavior = JsonRequestBehavior.DenyGet; 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     if (context == null) 
      throw new ArgumentNullException("context"); 

     if (JsonRequestBehavior == JsonRequestBehavior.DenyGet 
      && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) 
     { 
      throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); 
     } 

     HttpResponseBase response = context.HttpContext.Response; 

     response.ContentType = !string.IsNullOrEmpty(ContentType) 
            ? ContentType 
            : "application/json"; 

     if (ContentEncoding != null) 
      response.ContentEncoding = ContentEncoding; 

     if (Data != null) 
     { 
      var writer = new JsonTextWriter(response.Output) { Formatting = Formatting }; 

      var serializer = JsonSerializer.Create(SerializerSettings); 
      serializer.Serialize(writer, Data); 

      writer.Flush(); 
     } 
    } 
} 

信用:https://gist.github.com/jpoehls/1424538

+0

这是完美的!我最终通过使用'response.Write(JsonConvert.SerializeObject(this.Data))'而不是'JsonTextWriter'和'JsonSerializer'来实现更简单的版本。我永远不需要使用任何特殊的'JsonSerializerSettings'或'Formatting',并且与作家一起工作总是让我觉得过于复杂。 –

0

答案就在这里:How to force ASP.NET Web API to always return JSON?

摘录:

全部清除格式化,并添加Json的格式化回来。

GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter()); 编辑

我将它添加到Application_Start()中的Global.asax中。

+0

我没有使用Web API。我的控制器上的端点包括ViewResults,Json字符串和文件结果,所以我不认为这对我有用。 –