using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace System.Web.Mvc
{
internal class JsonNetResult : JsonResult
{
static IList<JsonConverter> DefaultConverters = new List<JsonConverter>()
{
new StringEnumConverter(), //new StringEnumConverter() { CamelCaseText = true },
new IsoDateTimeConverter(),
};
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
this.SerializerSettings = new JsonSerializerSettings()
{
Converters = DefaultConverters,
//ContractResolver = new CamelCasePropertyNamesContractResolver(),
};
}
public JsonNetResult(JsonResult original)
: this()
{
this.ContentEncoding = original.ContentEncoding;
this.ContentType = original.ContentType;
this.JsonRequestBehavior = original.JsonRequestBehavior;
this.Data = original.Data;
}
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;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
internal static class ControllerExtensions
{
public static JsonResult JsonNet(this Controller controller, JsonResult result)
{
return new JsonNetResult(result);
}
}
}
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace System.Web.Mvc
{
internal class JsonNetAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as JsonResult;
if (result != null) filterContext.Result = new JsonNetResult(result);
}
}
}