我同意上述 cmets 中的 AWinkle - 最好的方法是将反序列化为 DateTimeOffset 而不是 DateTime - 这样,您可以根据需要显示它。
也就是说,我将这个想法用于一种可能的方法,即使用自定义 JSON 类型转换器来获得您想要的时区剥离行为。这是我敲出的一个快速示例,它似乎按照您的要求进行。
/// <summary>
/// Custom converter for returning a DateTime which has been stripped of any time zone information
/// </summary>
public class TimezonelessDateTimeConverter : DateTimeConverterBase {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException("An exercise for the reader...");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
// We'll make use of Json.NET's own IsoDateTimeConverter so
// we don't have to re-implement everything ourselves.
var isoConverter = new IsoDateTimeConverter();
// Deserialise into a DateTimeOffset which will hold the
// time and the timezone from the JSON.
var withTz = (DateTimeOffset)isoConverter.ReadJson(reader, typeof(DateTimeOffset), existingValue, serializer);
// Return the DateTime component. This will be the original
// datetime WITHOUT timezone information.
return withTz.DateTime;
}
}
然后可以这样使用:
/// <summary>
/// Nonsense class just to represent your data. You'd implement the JsonConverter
/// attribute on your own model class.
/// </summary>
public class Sample {
[JsonConverter(typeof(TimezonelessDateTimeConverter))]
public DateTime EventDate { get; set; }
}
//
// And a sample of the actual deserialisation...
///
var json = "{ \"EventDate\": \"2017-05-05T11:35:44-07:00\" }";
var settings = new JsonSerializerSettings {
DateParseHandling = DateParseHandling.DateTimeOffset
};
var deserialised = JsonConvert.DeserializeObject<Sample>(json, settings);
Console.WriteLine(deserialised.EventDate);
这将输出05/05/2017 11:35:44。
这绝对不是最可靠的方法,我几乎可以肯定有些事情我没有考虑到 - 并且可能应该进行更彻底的测试以确保没有一些可怕的副作用。但希望这是一个可能的解决方案的起点,并为您指明正确的方向。
附:如果您还序列化回 JSON,则还需要实现 WriteJson 方法。我没有做那个,所以现在它只朝一个方向发展。