MongoDB custom serializer implementation

筅森魡賤 提交于 2019-11-30 19:24:41
fhusb

I figured this out in the end. I should have used bsonReader.GetCurrentBsonType() instead of bsonReader.CurrentBsonType. This reads the BsonType in from the buffer rather than just looking at the last thing there. I also fixed a subsequent bug derserializing. The updated method looks like this:

public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) {
    if (nominalType != typeof(Calendar) || actualType != typeof(Calendar))
        throw new BsonSerializationException();

    if (bsonReader.GetCurrentBsonType() != BsonType.Document)
        throw new FileFormatException();

    bsonReader.ReadStartDocument();
    var id = bsonReader.ReadString("_id");
    bsonReader.ReadName();
    var ser = new ArraySerializer<DateTime>();
    var holidays = (DateTime[])ser.Deserialize(bsonReader, typeof(DateTime[]), null);
    bsonReader.ReadEndDocument();
    return new Calendar(id, holidays);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!