解析以T24:00:00Z结尾的JSON日期 [英] Parsing JSON dates that end in T24:00:00Z

查看:184
本文介绍了解析以T24:00:00Z结尾的JSON日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个API,该API使用24:00:00作为datetime的时间部分返回给我ISO日期.

I'm hitting an API which is returning to me ISO dates using 24:00:00 as the time portion of the datetime.

我正在使用JSON.NET,但是当我尝试解析此日期时间时,它当前正在爆炸.从API返回的信息如下:

I'm using JSON.NET, but when I try to parse this datetime, it is currently blowing up. The return from the API is the following:

{
   "endTs":"2015-07-30T24:00:00Z"
}

我希望将其解析为"2015-07-31 12:00:00AM",但是我目前收到以下错误:

I would expect to parse this as "2015-07-31 12:00:00AM", but instead I get the following error currently:

Could not convert string to DateTime: 2015-07-30T24:00:00Z. Path 'endTs'...

推荐答案

更新

此问题已在Json.NET 8.0.1中修复.从发行说明:

This is fixed in Json.NET 8.0.1. From the Release Notes:

修复-固定读取24小时午夜ISO日期

Fix - Fixed reading 24 hour midnight ISO dates

原始答案

由于DateTime.Parse()本身在日期&上引发了异常.在这种格式下,您可以创建自己的IsoDateTimeConverter 检查并处理这种情况:

Since DateTime.Parse() itself throws an exception on a date & time in this format, you could create your own subclass of IsoDateTimeConverter that checks for and handles this case:

public class FixMidnightDateTimeConverter : IsoDateTimeConverter
{
    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)
    {
        Type type = (Nullable.GetUnderlyingType(objectType) ?? objectType);
        bool isNullable = (Nullable.GetUnderlyingType(objectType) != null);

        var token = JToken.Load(reader);
        if (token == null || token.Type == JTokenType.Null)
        {
            if (!isNullable)
                throw new JsonSerializationException(string.Format("Null value for type {0} at path {1}", objectType.Name, reader.Path));
            return null;
        }

        // Fix strings like "2015-07-30T24:00:00Z"
        if (token.Type == JTokenType.String)
        {
            const string midnight = "T24:00:00Z";
            var str = ((string)token).Trim();
            if (str.EndsWith(midnight))
            {
                var date = (DateTime?)(JValue)(str.Remove(str.Length - midnight.Length) + "T00:00:00Z");
                if (date != null)
                {
                    return date.Value.AddDays(1);
                }
            }
        }

        using (var subReader = token.CreateReader())
        {
            while (subReader.TokenType == JsonToken.None)
                subReader.Read();
            return base.ReadJson(subReader, objectType, existingValue, serializer); // Use base class to convert
        }
    }
}

在转换器级别执行此操作可避免在修改字符串字段中的数据时可能出现的问题.

Doing this at the converter level avoids problems that might arise with modifying data inside string fields.

然后将其注册为全局转换器直接将其传递给JsonConvert .

Then register it as a global converter or pass it to JsonConvert directly.

这篇关于解析以T24:00:00Z结尾的JSON日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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