json.net序列化字段datetime为mvc 4

时间:2013-11-05 17:44:49

标签: .net asp.net-mvc json json.net

如何使asp.net mvc 4做json.net序列化日期时间字段,如

/Date(122818919)/

我想将序列化程序从MVC更改为json.net,但保留一些属性的现有序列化。也许现有转换器?

1 个答案:

答案 0 :(得分:2)

这很容易做到。当您启动序列化程序时,将设置对象传递给它。

        JsonSerializerSettings _settings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Error,
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
        };

        JsonSerializer _scriptSerializer = JsonSerializer.Create(_settings);

我所做的是创建一个新的JsonNetResult并将其应用于...

public class JsonNetResult : JsonResult
{
    private static JsonSerializerSettings _settings;
    private static JsonSerializer _scriptSerializer;
    static JsonNetResult()
    {
        _settings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Error,
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
        };

        _scriptSerializer = JsonSerializer.Create(_settings);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null) throw new ArgumentNullException("context");            
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

        if (this.ContentEncoding != null)
            response.ContentEncoding = this.ContentEncoding;
        if (this.Data == null)
            return;

        using (StringWriter sw = new StringWriter())
        {
            _scriptSerializer.Serialize(sw, this.Data);
            response.Write(sw.ToString());
        }
    }
}

这使您的控制器代码变得非常简单。

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

这将允许您对所有请求执行此操作。如果你想在一个对象的一个​​属性上更改它,以下应该可以解决问题。

    public class SomeObject
    {
        [Newtonsoft.Json.JsonProperty(ItemConverterType = typeof(Newtonsoft.Json.Converters.JavaScriptDateTimeConverter))]
        public DateTime Time { get; set; }
    }