代码之家  ›  专栏  ›  技术社区  ›  tags2k

从Newtonsoft的JSON序列化程序解析JSON DateTime

  •  35
  • tags2k  · 技术社区  · 17 年前

    我使用Newtonsoft的JSON序列化程序序列化了一个对象,日期时间如下:

    /Date(1237588418563+0000)/
    

    当我在上面输入$.evalJSON()时,它是一个对象,但在它上面找不到任何像toutString这样的普通日期方法。

    你知道我能用这个做什么吗?

    7 回复  |  直到 17 年前
        1
  •  79
  •   James Newton-King dbc    13 年前

    使用Json.NET附带的JSONConverter之一处理日期以获得更好的格式。JavaScriptDateTimeConverter将自动为您提供JavaScript日期。

    public class LogEntry    
    {    
      public string Details { get; set; }    
      public DateTime LogDate { get; set; }
    }
    
    [Test]
    public void WriteJsonDates()
    {    
      LogEntry entry = new LogEntry    
      {    
        LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),    
        Details = "Application started."    
      };    
    
    
      string defaultJson = JsonConvert.SerializeObject(entry);    
      // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}     
    
      string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());    
      // {"Details":"Application started.","LogDate":new Date(1234656000000)}
    
      string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());    
      // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}    
    }
    

    文档: Serializing Dates in JSON with Json.NET

        2
  •  16
  •   Johann    13 年前

    我想出了一种可能对某些人有用的不同方法。基本上我自己创造 自定义数据转换器 我需要的时候打电话给你。转换器采用2个参数,一种日期格式,例如。 yyyy-MM-dd HH:mm:ss 以及TimeZoneInfo,它允许我将日期从UTC转换为用户的时区:

    public class JSONCustomDateConverter : DateTimeConverterBase
    {
        private TimeZoneInfo _timeZoneInfo;
        private string _dateFormat;
    
        public JSONCustomDateConverter(string dateFormat, TimeZoneInfo timeZoneInfo)
        {
            _dateFormat = dateFormat;
            _timeZoneInfo = timeZoneInfo;
        }
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(value), _timeZoneInfo).ToString(_dateFormat));
            writer.Flush();
        }
    

    您可以这样使用它:

     var jsonString = JsonConvert.SerializeObject(myObject, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Converters = new List<JsonConverter>() { new JSONCustomDateConverter("yyyy-MM-dd HH:mm:ss", loggedUser.Timezone) } });
    

    显然,如果您只需要自定义日期格式,就可以删除任何与时区相关的内容。让我知道这有帮助!

        3
  •  15
  •   Anderson    14 年前

    从Newtonsoft Json.Net版本4.5r5开始,您使用JsonPropertyAttribute类并设置其ItemConverterType属性。 用法:

    // class to be serialized
    public class MyClass
    {
        [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
        public DateTime? DateTime1;
        public DateTime? DateTime2;
    }
    

    正如我所观察到的,这将为该类中的所有属性设置DateTimeConverter,而不仅仅是声明之前的属性。

        4
  •  3
  •   Timothy S. Van Haren Prashant    10 年前

    new Date(yourDate.substr(yourDate.indexOf("(") + 1, 13) - 0));
    

    它看起来像Unix时间戳,javascript可以轻松地将其转换为日期对象。这个 - 0 只是让javascript处理 substr 输出为整数。。。我想你可以 Number() 如果你不喜欢它的外观,也可以

        5
  •  1
  •   Peter O. Manuel Pinto    13 年前

    JSON对象包含如下内容:

    var data = {"CreatedDate":"/Date(1327572000000-1000)/"});
    
     ///
    var oddDateTimeZone = data.CreatedDate;
    var utcDateTime = oddDateTimeZone.substr(oddDateTimeZone.indexOf("(")+1, 13);
    var utcZone = oddDateTimeZone.substr(oddDateTimeZone.indexOf("-")+1, 4);
    var utcDateTimeZone = new Date(Number(utcDateTime)-(Number(utcZone)));
    

    但是,仍然最好修复JSON对象,以便在不使用eval()或window[]之类的东西的情况下启动日期函数。也许在jQuery中。不确定。

    不要忘记偏移量可能是 + -

        6
  •  -1
  •   Ben    11 年前

    对不起,我简化了一点@James Newton King

    string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);    
    
        7
  •  -2
  •   Liam Joshua    7 年前
    ObjectMapper mapper = new ObjectMapper();
    
    mapper.registerModule(new JavaTimeModule());
    
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    

    这对我有用