是否可以使用Json.NET将DateTimeOffset序列化为zulu时间字符串?

Zoo*_*oom 10 c# datetimeoffset json.net

我有一个DateTimeOffset对象"05/06/2014 05:54:00 PM -04:00".

使用Json.NET和ISO设置进行序列化时,我得到"2014-05-06T17:54:00-04:00".

我想要的是该字符串"2014-05-06T21:54:00Z"的UTC/Zulu版本.

但是,我找不到任何序列化程序设置来实现此目的.我知道对于DateTime序列化,我可以设置DateTimeZoneHandling = DateTimeZoneHandling.Utc以具有Zulu格式.但是,DateTimeOffset没有这样的设置选项.我错过了什么吗?或者我是否必须为此创建自定义覆盖?

Bri*_*ers 17

尝试使用IsoDateTimeConverterJson.Net附带的:

var date = new DateTime(2014, 5, 6, 17, 24, 55, DateTimeKind.Local);
var obj = new { date = new DateTimeOffset(date) };

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new IsoDateTimeConverter 
{ 
    DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ", 
    DateTimeStyles = DateTimeStyles.AdjustToUniversal 
});

string json = JsonConvert.SerializeObject(obj, settings);
Console.WriteLine(json);
Run Code Online (Sandbox Code Playgroud)

输出:

{"date":"2014-05-06T22:24:55Z"}
Run Code Online (Sandbox Code Playgroud)


Tho*_*que 7

您可以编写这样的自定义转换器:

class UtcDateTimeOffsetConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is DateTimeOffset)
        {
            var date = (DateTimeOffset)value;
            value = date.UtcDateTime;
        }
        base.WriteJson(writer, value, serializer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        object value = base.ReadJson(reader, objectType, existingValue, serializer);
        if (value is DateTimeOffset)
        {
            var date = (DateTimeOffset)value;
            value = date.ToLocalTime();
        }
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用JsonConverter属性将其应用于您想要的属性:

[JsonConverter(typeof(UtcDateTimeOffsetConverter))]
public DateTimeOffset Date { get; set; }
Run Code Online (Sandbox Code Playgroud)