【发布时间】:2014-07-18 23:07:43
【问题描述】:
我有一个对象作为属性,我为其创建了自定义序列化程序。它所做的只是调用 ToString,因为我想将数据表示为我的集合中的字符串。
cm.MapMember(c => c.myObjectProperty).SetSerializer(new ObjectToStringSerializer() );
上面只调用一次,保存数据时效果很好。我可以按预期看到带有字符串值的父对象。
这是基本的序列化程序:
public class ObjectToStringSerializer : IBsonSerializer {
#region IBsonSerializer Members
public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
if (bsonReader.State == MongoDB.Bson.IO.BsonReaderState.Type && bsonReader.CurrentBsonType != MongoDB.Bson.BsonType.Null)
return Activator.CreateInstance(nominalType, new object[] { bsonReader.ReadString() });
return null;
}
public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
if( bsonReader.State == MongoDB.Bson.IO.BsonReaderState.Type && bsonReader.CurrentBsonType != MongoDB.Bson.BsonType.Null)
return Activator.CreateInstance(nominalType, new object[] { bsonReader.ReadString() });
return null;
}
public IBsonSerializationOptions GetDefaultSerializationOptions()
{
throw new NotImplementedException();
}
public void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
if (value != null)
{
bsonWriter.WriteString(value.ToString());
}
else
bsonWriter.WriteNull();
}
#endregion
}
当我尝试从集合中取回父对象时,会引发异常:
ReadBsonType 只能在 State 为 Type 时调用,不能在 State 为 Value 时调用。
而且堆栈跟踪看起来不像是在尝试调用我的自定义序列化程序的反序列化方法。
为了让我希望调用我的反序列化方法,我缺少什么?我尝试添加一个简单的序列化提供程序,但我认为这不对。我也试过 重新注册序列化程序。
BsonSerializer.RegisterSerializer(typeof(myObjectPropertyType), new ObjectToStringSerializer());
【问题讨论】:
标签: c# mongodb serialization bson