【问题标题】:json.net serialize field datetime as mvc 4 didjson.net 像 mvc 4 那样序列化字段日期时间
【发布时间】:2013-11-05 17:44:49
【问题描述】:

如何让 json.net 像 asp.net mvc 4 那样序列化日期时间字段,类似于

/Date(122818919)/

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

【问题讨论】:

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


    【解决方案1】:

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

            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; }
        }
    

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多