如何序列化没有空字段或空对象的 BsonDocument?
例如
{
"key1" : null,
"key2": 100
}
应序列化为:
{
"key2": 100
}
此外,空对象应该被忽略:
{
"key1" : { },
"key2": 100
}
应序列化为:
{
"key2": 100
}
要忽略
null
值,只需指定 BsonIgnoreIfNull
属性
public class Entity
{
[BsonIgnoreIfNull]
public BsonDocument Key1 { get; set; }
[BsonIgnoreIfNull]
public string Key2 { get; set; }
}
或通过静态配置:
BsonClassMap.RegisterClassMap<Entity>(b =>
{
b.AutoMap();
b.GetMemberMap<BsonDocument>(i => i.Key1).SetIgnoreIfNull(ignoreIfNull: true);
b.GetMemberMap<string>(i => i.Key2).SetIgnoreIfNull(ignoreIfNull: true);
});
但是,要忽略空文档值,您必须创建一个自定义序列化程序,如下所示:
// use it as a starting point
public class CustomEntitySerializer : SerializerBase<Entity>
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Entity value)
{
context.Writer.WriteStartDocument();
foreach (var field in value.GetType().GetProperties())
{
var fieldValue = field.GetValue(value);
if (fieldValue == null ||
(fieldValue is BsonValue v && v.IsBsonNull) ||
fieldValue is BsonDocument d && d.ElementCount == 0)
{
// skip
}
else
{
context.Writer.WriteName(field.Name);
var serializer = BsonSerializer.LookupSerializer(field.PropertyType);
serializer.Serialize(context, args, fieldValue);
}
}
context.Writer.WriteEndDocument();
}
}
然后以这种方式应用这个序列化器:
[BsonSerializer(typeof(CustomEntitySerializer))]
public class Entity
{
[BsonIgnoreIfNull]
public BsonDocument Key1 { get; set; }
[BsonIgnoreIfNull]
public string Key2 { get; set; }
}
或通过全局静态配置:
BsonSerializer.RegisterSerializer<Entity>(new CustomEntitySerializer());