Ignore UTC offsets when deserializing with Json.NET

心不动则不痛 提交于 2019-12-12 20:50:28

问题


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.

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

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.


回答1:


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

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

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



来源:https://stackoverflow.com/questions/37318712/ignore-utc-offsets-when-deserializing-with-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!