使用 JSON.NET 作为默认的序列化器来序列化 JSON 而不是默认的 Javascript 序列化器:
如果它为NULL,这将处理发送数据的场景。
例如
在你的操作方法中代替这个:
return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet)
你需要在你的action方法中写下这个:
return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, null, null);
注意:上述函数中的第2个和第3个参数null是为了方便Controller类中Json方法的重载。
此外,您不需要在上述所有操作方法中检查 null:
if (portfolioManagerPortalData.salesData.myYTDSalesClients == null)
{
returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
}
else
{
returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
}
下面是 JsonNetResult 类的代码。
public class JsonNetResult : JsonResult
{
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings();
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
如果您的项目中有任何代码,您还需要在 BaseController 中添加以下代码:
/// <summary>
/// Creates a NewtonSoft.Json.JsonNetResult object that serializes the specified object to JavaScript Object Notation(JSON).
/// </summary>
/// <param name="data"></param>
/// <param name="contentType"></param>
/// <param name="contentEncoding"></param>
/// <returns>The JSON result object that serializes the specified object to JSON format. The result object that is prepared by this method is written to the response by the ASP.NET MVC framework when the object is executed.</returns>
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}