是否可以告诉Json.NET反序列化2012-07-19'到零偏移的DateTimeOffset值?
要重现的代码示例:
public class SingleDateTimeField
{
public DateTimeOffset StartDateTime { get; set; }
}
[Test]
public void Convert()
{
// Given
var content = @"{""startDateTime"":""2012-07-19""}";
var jsonSerializerSettings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateParseHandling = DateParseHandling.DateTimeOffset,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
// When
var obj = JsonConvert.DeserializeObject<SingleDateTimeField>(content, jsonSerializerSettings);
// Then
var expected = new DateTimeOffset(2012, 07, 19, 0, 0, 0, TimeSpan.Zero);
Assert.That(obj.StartDateTime, Is.EqualTo(expected));
}
失败
预计:2012-07-19 00:00:00.000 + 00:00 但是:2012-07-19 00:00:00.000 + 03:00
请注意,时区为+03:00
我可以通过使用专门的转换器(下面的例子)来实现它,但是设置DateTimeZoneHandling = DateTimeZoneHandling.Utc
应该已经转换了这个UTC吗?不需要AssumeUtc
转换器。
public class AssumeUtc : IsoDateTimeConverter
{
public AssumeUtc()
{
DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal;
}
}
public class SingleDateTimeField
{
[JsonConverter(typeof(AssumeUtc))]
public DateTimeOffset StartDateTime { get; set; }
}