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

MongoDB中yyyy-MM-dd HH:mm:ss格式日期字符串反序列化失败咨询

解决MongoDB反序列化yyyy-MM-dd HH:mm:ss格式日期的问题

问题根源在于MongoDB .NET驱动默认仅支持ISO 8601格式(如yyyy-MM-ddTHH:mm:ss)的字符串日期反序列化,而你的数据是空格分隔的yyyy-MM-dd HH:mm:ss格式,因此需要自定义序列化器适配该格式。

步骤1:编写自定义DateTime序列化器

创建实现IBsonSerializer<DateTime>的类,专门处理指定格式的日期解析与序列化:

using MongoDB.Bson.Serialization;
using MongoDB.Bson.IO;
using System.Globalization;

public class CustomDateTimeSerializer : IBsonSerializer<DateTime>
{
    private const string TargetFormat = "yyyy-MM-dd HH:mm:ss";
    private readonly DateTimeStyles _parseStyles = DateTimeStyles.None;

    public Type ValueType => typeof(DateTime);

    public DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var currentType = context.Reader.GetCurrentBsonType();
        switch (currentType)
        {
            case BsonType.String:
                var dateStr = context.Reader.ReadString();
                if (DateTime.TryParseExact(dateStr, TargetFormat, CultureInfo.InvariantCulture, _parseStyles, out DateTime parsedDate))
                {
                    return parsedDate;
                }
                throw new FormatException($"日期格式错误:'{dateStr}' 不符合 {TargetFormat} 格式");
            case BsonType.DateTime:
                // 兼容可能以DateTime类型存储的情况
                return context.Reader.ReadDateTime().ToLocalTime();
            default:
                throw new NotSupportedException($"无法从 {currentType} 类型反序列化为DateTime");
        }
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
    {
        // 序列化时保持相同格式,若不需要可按需修改
        context.Writer.WriteString(value.ToString(TargetFormat, CultureInfo.InvariantCulture));
    }

    // 实现非泛型IBsonSerializer接口的方法
    object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return Deserialize(context, args);
    }

    void IBsonSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        Serialize(context, args, (DateTime)value);
    }
}

步骤2:在实体类中应用自定义序列化器

修改UserFile类的UploadTime属性,替换原有BsonDateTimeOptions特性,绑定自定义序列化器:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class UserFile
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonElement("_id")]
    public string? Id { get; set; }

    [BsonElement("upload_time")]
    [BsonSerializer(typeof(CustomDateTimeSerializer))] // 关联自定义序列化器
    public DateTime UploadTime { get; set; }

    [BsonElement("data")]
    public BsonDocument? Data{ get; set; }
}

可选:全局注册序列化器

如果多个实体类都需要处理该日期格式,可在初始化MongoDB客户端时全局注册序列化器,避免重复添加特性:

using MongoDB.Driver;
using MongoDB.Bson.Serialization;

var clientSettings = MongoClientSettings.FromConnectionString("你的MongoDB连接字符串");
clientSettings.SerializerRegistry = BsonSerializerRegistry.Create(new BsonSerializerConfiguration
{
    Serializers = { new CustomDateTimeSerializer() }
});
var mongoClient = new MongoClient(clientSettings);

配置完成后,驱动即可正确解析yyyy-MM-dd HH:mm:ss格式的日期字符串,同时保持序列化格式一致(若无需该序列化格式,可修改序列化器的Serialize方法逻辑)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:48:27