由于各种原因,我已经从ASP.NET MVC的内置JSON序列化器(返回一个 (请参见下面的编辑))切换到Newtonsoft。直到开始测试后,我才意识到前者返回JavaScript对象文字,而Newtonsoft返回JSON格式的string。System.Web.Mvc.JsonResult
对象
我喜欢不必在客户端解析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)而不是内置的序列化程序。
只需编写一个使用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();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句