C#MongoDB驱动程序序列化 - 使用二进制文件

时间:2014-06-25 20:51:51

标签: c# mongodb serialization

我有一个"复杂的"包含我想要序列化为二进制的属性的类:

public class MyClassA{
  public MyClassB myClassB {get;set;}
  public MyClassB myClassC {get;set;}
  [BsonIgnore]
  public MyClassB myClassD {get;set;}
  private byte[] myClassDBin {get;set}
}

我想在RAM中只保留myClassD对象,但我还想仅序列化myClassDBin对象。第一个条件很容易在custructor中实现:

public class MyClassA{
  public MyClassB myClassB {get;set;}
  public MyClassB myClassC {get;set;}
  [BsonIgnore]
  public MyClassB myClassD {get;set;}
  private byte[] myClassDBin {get;set}

  [BsonConstructor]
  public MyClassA(MyClassB myClassB, MyClassC myClassC, MyClassDBin[] myClassDBin)
  {
     this.myClassB = myClassB;
     this.myClassC = myClassC;
     this.myClassDBin = myClassBin;
     if(this.myClassDBin != null)
     {
        using(MemoryStream stream = new MemoryStream(this.myClassDBin))
        {
           this.myClassD = myClassD.Load(stream);//custom serializer
        }
     }
     this.myClassDBin = null; //Keep only one object in RAM
  }
}

这对于反序列化来说真的很好,但序列化呢?如果我希望myClassDBin被序列化,我需要它一直不为null。我需要实现自定义序列化程序吗?这可能是一个很长的任务,因为类myClassB / C / D是大类,使用自动化器很容易....有没有像XML一样的接口,我们可以在序列化之前实现它?

1 个答案:

答案 0 :(得分:1)

我认为我必须实现整个序列化程序,但我从Robert Sam那里读到了this post,这对我帮助很大。我只是写了一个自定义序列化器:

internal class MesureSerializer : IBsonSerializer
{
  private readonly IBsonSerializer _classMapSerializer;

  public MesureSerializer()
  {
     var classMap = BsonClassMap.LookupClassMap(typeof(MyClassA));
     _classMapSerializer = new BsonClassMapSerializer(classMap);
  }

  object IBsonSerializer.Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
  {
     return _classMapSerializer.Deserialize(bsonReader, nominalType, actualType, options);
  }

  void IBsonSerializer.Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
  {
     MyClassA item = (MyClassA)value;
     if(item.myClassD != null)
     {
        using(MemoryStream stream = new MemoryStream())
        {
           item.myClassD.Save(item.myClassD, stream);
           mesure.myClassDBin = stream.ToArray();
        }
     }
     else
     {
        item.myClassDBin = null;
     }
     _classMapSerializer.Serialize(bsonWriter, nominalType, item, options);
     item.myClassDBin = null;
  }


  object IBsonSerializer.Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
  {
     return _classMapSerializer.Deserialize(bsonReader, nominalType, options);
  }

  IBsonSerializationOptions IBsonSerializer.GetDefaultSerializationOptions()
  {
     return _classMapSerializer.GetDefaultSerializationOptions();
  }
}

就这么简单!