使用Json.NET反序列化时忽略UTC偏移量 [英] Ignore UTC offsets when deserializing with Json.NET

查看:64
本文介绍了使用Json.NET反序列化时忽略UTC偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用ASP.NET Web API 2编写了一个可接收日期的REST端点.后端系统没有UTC时间或DST的概念,数据库中存储的日期只是英国的日期和时间.

I've written a REST endpoint with ASP.NET Web API 2 that receives dates. The backend system has no concept of UTC times or DST, the dates stored in the database are just the UK date and time.

为端点提供数据的网站在发送到端点的数据中包含UTC偏移值(例如,日期看起来像"1939-01-08T00:00:00 + 01:00").如果在冬天输入了夏季日期,或者相反(由于DST的调整),就会发生这种情况.

The website feeding the endpoint, however, is including UTC offset values in the data sent to the end point (e.g. a date looks like "1939-01-08T00:00:00+01:00"). This happens when a summer date is entered in the winter or vice-versa (because of the adjustment for DST).

是否可以将JSON解串器设置为完全忽略那些UTC偏移值?我在文档此处和示例此处,并尝试了所有不同的枚举选项,但没有一个给我该行为我在找.

Is it possible for me to set the JSON deserializer to completely ignore those UTC offset values? I've looked at the docs here and the examples here and tried all of the different enum options, but none of them are giving me the behaviour I'm looking for.

推荐答案

如果日期解析无法按照您想要的方式进行,则可以将其关闭,然后使用自定义的JsonConverter来处理日期.

If the date parsing isn't working the way you want, you can turn it off and use a custom JsonConverter to handle the dates instead.

以下是应该执行此工作的转换器:

Here is a converter that should do the job:

class OffsetIgnoringDateConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(DateTime) || objectType == typeof(DateTime?));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string rawDate = (string)reader.Value;
        if (rawDate == null) return existingValue;
        if (rawDate.Length > 19) rawDate = rawDate.Substring(0, 19);
        DateTime date = DateTime.ParseExact(rawDate, "yyyy'-'MM'-'dd'T'HH':'mm':'ss", 
                                 CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);
        return date;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

要将此转换器安装到Web API管道中,请在Global.asax中的Application_Start()方法中添加以下内容:

To install this converter into the Web API pipeline, add the following to your Application_Start() method in Global.asax:

var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DateParseHandling = DateParseHandling.None;
jsonSettings.Converters.Add(new OffsetIgnoringDateConverter());

这是一个演示(控制台应用程序): https://dotnetfiddle.net/kt9pFl

Here is a demo (console app): https://dotnetfiddle.net/kt9pFl

这篇关于使用Json.NET反序列化时忽略UTC偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆