You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Json反序列化DateTime异常:三位秒值格式解析失败求解

问题根源

你遇到的日期字符串2021-04-13T19:58:042.633Z是不符合ISO 8601标准的非法格式——正常秒数范围是00-59,这里错误地写成了三位数字(042),本质是把42秒多写了一个前导零,导致默认日期解析逻辑无法识别。仅修改DateFormatString无法解决问题,因为格式字符串只能匹配合法的日期结构。


解决方法:自定义日期转换器修正非法格式

通过编写自定义JsonConverter,先手动修正非法的日期字符串,再进行标准解析:

1. 创建自定义转换器

using System;
using System.Globalization;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class InvalidSecondsDateTimeConverter : DateTimeConverterBase
{
    // 修正后要匹配的合法格式(24小时制+毫秒+时区Z)
    private const string ValidFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
    // 匹配非法三位秒格式的正则:捕获日期前缀、三位秒、毫秒后缀
    private static readonly Regex InvalidSecondsRegex = new Regex(@"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}):(\d{3})(\.\d{3}Z)", RegexOptions.Compiled);

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.Value is not string dateStr)
            return base.ReadJson(reader, objectType, existingValue, serializer);

        // 修正非法字符串:把三位秒(如042)截取后两位转为合法秒数(42)
        string correctedDate = InvalidSecondsRegex.Replace(dateStr, match => 
        {
            string invalidSec = match.Groups[2].Value;
            string validSec = invalidSec.Substring(1);
            return $"{match.Groups[1]}:{validSec}{match.Groups[3]}";
        });

        // 用标准格式解析修正后的字符串
        return DateTime.ParseExact(correctedDate, ValidFormat, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var date = (DateTime)value;
        // 序列化时输出标准格式
        writer.WriteValue(date.ToString(ValidFormat, CultureInfo.InvariantCulture));
    }
}

2. 在序列化设置中启用转换器

替换原来的DateFormatString配置,将自定义转换器加入JsonSerializerSettings:

JsonSerializerSettings serSettings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    Formatting = Formatting.Indented,
    Converters = new List<JsonConverter> { new InvalidSecondsDateTimeConverter() }
};

额外提醒

你原来的DateFormatString使用了hh(12小时制),但输入的日期是24小时制(如13:11、19:58),这是潜在问题——若遇到09:00这类上午时间,解析会出错,建议统一用HH(24小时制)匹配输入格式。

内容的提问来源于stack exchange,提问作者Oleg Sh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:45:40