使用简单对象自定义复杂C#对象的序列化

时间:2014-06-21 13:08:46

标签: c# .net mongodb serialization mongodb-.net-driver

我正在使用QuickGraph中名为AdjacencyGraph的实用程序类,它具有复杂的内部结构。

我不关心复杂类的所有内部属性,我无法将其更改为来自nuget包 - 至多在我的数据库中我只关心存储可用于重建的Dependency对象数组AdacencyGraph:

public class Dependency
{
    public Dependency(string source, string target)
    {
        this.Source = source;
        this.Target = target;
    }

    public string Source { get; set; }
    public string Target { get; set; }
}

在序列化时,我需要做的就是以下代码:

void Serialize(Dependencies toSerialize)
{
    var toBeStored = toSerialize.GetAllDependencies();
    // write this to mongodb somehow
}

反序列化构建Dependencies对象:

Dependencies Deserialize(IEnumerable<Dependency> hydrateFrom)
{
    var dependencies = new Dependencies();

    foreach(var d in hydrateFrom)
    {
        dependencies.SetRequiresFor(d.Source, d.Target);
    }
}

问题

如何拦截序列化过程和输出?

其他信息

我将AdjacencyGraph包装在一个列出所有Dependency对象的类中,并且也可以接受一个Dependency对象列表。

class Dependencies
{
    private AdjacencyGraph<string, Edge<string>> relationshipGraph = new AdjacencyGraph<string, Edge<string>>();

    public void SetRequiresFor(SkuId on, SkuId requires)
    {
        var toAdd = new Edge<string>(on.Value, requires.Value);
        this.relationshipGraph.AddVerticesAndEdge(toAdd);

    }

    public IEnumerable<Dependency> GetAllDependencies()
    {
        foreach(var edge in this.relationshipGraph.Edges)
        {
            yield return new Dependency(edge.Source, edge.Target);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您需要做三件事:

  1. 实施BsonSerializer
  2. 实施BsonSerializationProvider,将Dependencies指向序列化程序。 *
  3. 在应用程序的初始化中注册提供程序。
  4. BsonSerializer

    public class DependenciesBsonSerializer : BsonBaseSerializer
    {
        public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            // implement using bsonWriter
        }
    
        public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
        {
            // implement using bsonReader
        }
    }
    

    BsonSerializationProvider

    public sealed class BsonSerializationProvider : IBsonSerializationProvider
    {
        public IBsonSerializer GetSerializer(Type type)
        {
            if (type == typeof(Dependncies)
            {
                return new DependenciesBsonSerializer ();
            }
    
            return null;
        }
    }
    

    Registeration

    BsonSerializer.RegisterSerializationProvider(new BsonSerializationProvider());
    

    *您可以切断提供程序并使用BsonSerializer.RegisterSerializer直接注册序列化程序,但我仍然建议将所有序列化程序分组到一个提供程序中。