0

如何像 asp.net mvc 4 那样使 json.net 序列化日期时间字段,例如

/Date(122818919)/

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

4

1 回答 1

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; }
    }
于 2013-11-05T17:54:47.820 回答