我假设您指的是像这样的EmailAddress类:
我假设您指的是像这样的EmailAddress类:
[BsonSerializer(typeof(EmailAddressSerializer))]
public class EmailAddress
{
private string _value;
public EmailAddress(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
我使用了一个属性来将EmailAddress类与自定义序列化程序联系起来,它可以实现如下所示:
:
public class EmailAddressSerializer : BsonBaseSerializer
{
public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
if (bsonReader.GetCurrentBsonType() == BsonType.Null)
{
bsonReader.ReadNull();
return null;
}
else
{
var value = bsonReader.ReadString();
return new EmailAddress(value);
}
}
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
if (value == null)
{
bsonWriter.WriteNull();
}
else
{
var emailAddress = (EmailAddress)value;
bsonWriter.WriteString(emailAddress.Value);
}
}
}
您不能将EmailAddress作为根文档进行序列化(因为它不是文档...)。但是您可以在其他文档中嵌入一个EmailAddress。例如:
public class Person
{
public int Id { get; set; }
public EmailAddress EmailAddress { get; set; }
}
您可以使用以下代码进行测试:
以下是参考代码:
var person = new Person { Id = 1, EmailAddress = new EmailAddress("joe@xyz.com") }
var json = person.ToJson()
var rehyrdated = BsonSerializer.Deserialize<Person>(json)
生成的JSON/BSON文档如下:
{ "_id" : 1, "EmailAddress" : "joe@xyz.com" }