我有一个使用自定义 IBsonSerializer 和 Newtonsoft.Json 的干净解决方案。
在 BsonClassMap 上设置您的自定义序列化程序
map.MapProperty(member => member.Data)
.SetElementName("Data")
.SetSerializer(new DynamicSerializer());
或在物业上
[BsonSerializer(typeof(DynamicSerializer))]
public dynamic Data { get; set; }
并且只包括以下课程
public class DynamicSerializer : IBsonSerializer
{
#region Implementation of IBsonSerializer
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
return Deserialize(bsonReader, nominalType, null, options);
}
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType,
IBsonSerializationOptions options)
{
if (bsonReader.GetCurrentBsonType() != BsonType.Document) throw new Exception("Not document");
var bsonDocument = BsonSerializer.Deserialize(bsonReader, typeof(BsonDocument), options) as BsonDocument;
return JsonConvert.DeserializeObject<dynamic>(bsonDocument.ToJson());
}
public IBsonSerializationOptions GetDefaultSerializationOptions()
{
return new DocumentSerializationOptions();
}
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
var json = (value == null) ? "{}": JsonConvert.SerializeObject(value);
BsonDocument document = BsonDocument.Parse(json);
BsonSerializer.Serialize(bsonWriter, typeof(BsonDocument), document,options);
}
#endregion
}
InfoSlips - GlobalKinetic