从 Newtonsoft 的 JSON Serializer 解析 JSON DateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/668488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:13:01  来源:igfitidea点击:

Parsing JSON DateTime from Newtonsoft's JSON Serializer

jsondatetimeparsingjson.net

提问by tags2k

I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as:

我已经使用 Newtonsoft 的 JSON 序列化器序列化了一个对象,并且 DateTime 已经通过:

/Date(1237588418563+0000)/

When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it.

当我使用 $.evalJSON() 时,它是一个对象,但我找不到任何像 toUTCString 这样的普通 Date 方法。

Any ideas what I can do with this?

任何想法我可以用这个做什么?

回答by James Newton-King

Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date.

使用 Json.NET 附带的 JsonConverters 之一处理日期以获得更好的格式。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"}    
}

Documentation: Serializing Dates in JSON with Json.NET

文档:使用 Json.NET 序列化 JSON 中的日期

回答by Johann

I came up with a different approach which might be useful to some. Basically I create my own CustomDateConverterthat I call when I need it. The converter takes 2 parameters, a date format e.g. yyyy-MM-dd HH:mm:ssand a TimeZoneInfo, which allows me to convert the date from UTC to the user's time zone:

我想出了一种可能对某些人有用的不同方法。基本上,我创建了自己的CustomDateConverter,在需要时调用它。转换器采用 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();
    }

You can use it like this:

你可以这样使用它:

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

Obviously you could remove anything related to time zone if you only want custom date formatting. Let me know it that helped!

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

回答by Anderson

As of Newtonsoft Json.Net version 4.5r5 you use the JsonPropertyAttribute Class class and set its ItemConverterType Property property. Usage:

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

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

As I have observed this will set the DateTimeConverter for all properties in this class not just the one before which is declared.

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

回答by peirix

Ran into the same problem, and found a solution based on the link from Adam:

遇到了同样的问题,并根据 Adam 的链接找到了解决方案:

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

It looks like a Unix timestamp, which javascript is easily able to convert into a date object. The - 0is simply to make javascript treat the substroutput as an integer... I guess you could Number()it as well, if you don't like the looks of - 0

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

回答by PowerSparks

The JSON object contained something like this:

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

but, still it would be better to fix the JSON object so the date function fired without using something like eval() or window[]. Maybe in jQuery. Not sure.

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

Don't forget that the offset could be +and not just -for the offset!

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

回答by Ben

Sorry I simplify a bit @James Newton-King

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

string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);    

回答by Jayen Chondigara

ObjectMapper mapper = new ObjectMapper();

mapper.registerModule(new JavaTimeModule());

mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

This works for me

这对我有用