Home > Net >  Client cannot deserialize string date time
Client cannot deserialize string date time

Time:07-25

This error message occurs when getting the data from MongoDB. The format is yyyy-MM-dd HH:mm:ss. An error occurred while deserializing the UploadTime property of class UserFile: String '2022-07-25 15:49:18' was not recognized as a valid DateTime.

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

    [BsonElement("upload_time")]
    [BsonDateTimeOptions(Kind = DateTimeKind.Unspecified, Representation = BsonType.String)]
    public DateTime UploadTime { get; set; }

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

How to correctly deserialize date time string? I cannot change the value while insertion because that value is from another application.

CodePudding user response:

You can create a custom serializer to deserialize the string to a DateTime. In its simplest form, if you only want to deserialize, the following sample shows a custom serializer that reads the value:

public class CustomDateTimeSerializer : IBsonSerializer
{
  public Type ValueType => typeof(DateTime);

  public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
  {
    var str = context.Reader.ReadString();
    return DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
  }

  public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
  {
    throw new NotImplementedException();
  }
}

You can configure the property to use the serializer like this:

[BsonElement("upload_time")]
[BsonSerializer(typeof(CustomDateTimeSerializer))]
public DateTime UploadTime { get; set; }

Please note that in the sample, the DateTimeOptions attribute is removed because the simple serializer does not support the configuration with DateTimeOptions.

  • Related