简体   繁体   English

使用 MongoDB Bson 序列化器序列化 object 图

[英]Serializing object graph using MongoDB Bson serializer

I've been playing a little with the MongoDB Bson serializer, using the following piece of code:我一直在使用 MongoDB Bson 序列化程序,使用以下代码:

class Program
{
    public class myValue
    {
        public int Id = 0;
        public string Label = "";
    }

    public class myValueMap : Dictionary<string, myValue>
    {
    }

    public class myProdData
    {
        public myValueMap  Mapping { get; set; }

    }
    public class mySystemPosition
    {
        public string Text { get; set; }
        public myProdData ProdData { get; set; }

    }
    static void Main(string[] args)
    {
        BsonClassMap.RegisterClassMap<mySystemPosition>();
        BsonClassMap.RegisterClassMap<myProdData>();
        BsonClassMap.RegisterClassMap<myValueMap>();
        BsonClassMap.RegisterClassMap<myValue>();
        var o = new mySystemPosition()
                    {
                        ProdData = new myProdData()
                                       {
                                           Mapping = new myValueMap()
                                                        {
                                                            {"123", new myValue() {Id = 1, Label = "Item1"}},
                                                            {"345", new myValue() {Id = 2, Label = "Item2"}},
                                                        }
                                       }
                    };
        var bson = o.ToBson();

        var text = Encoding.ASCII.GetString(bson);
    }
}

however I don't seem to be able to get the myProdData.Mapping serialized....但是我似乎无法将 myProdData.Mapping 序列化....

Do I need to configure the MongoDB Bson serializer in a special way, to make this work?我是否需要以特殊方式配置 MongoDB Bson 串行器才能使其工作?

You no need to use BsonClassMap.RegisterClassMap if you no need custom serializtion( documentation ).如果您不需要自定义序列化( 文档),则无需使用BsonClassMap.RegisterClassMap All your classes will be desirialzied according to default rules.您的所有课程都将根据默认规则进行 desiialzied。

Also i am changed your example a little bit to get it work(i've replaces myValueMap class with Dictionary):另外,我稍微更改了您的示例以使其正常工作(我已将myValueMap class 替换为 Dictionary):

    public class myProdData
    {
        public  Dictionary<string, myValue> Mapping { get; set; }
    }

    static void Main(string[] args)
    {
        var o = new mySystemPosition()
        {
            ProdData = new myProdData()
            {
                Mapping = new Dictionary<string, myValue>()
                {
                    {"123", new myValue() {Id = 1, Label = "Item1"}},
                    {"345", new myValue() {Id = 2, Label = "Item2"}},
                }
            }
        };

        var json = o.ToJson();
        Console.WriteLine(json);
        Console.ReadKey();
    }

Here is console output(just well formatted):这是控制台输出(格式正确):

{
    "Text":null,
    "ProdData":{
        "Mapping":{
            "123":{
                "_id":1,
                "Label":"Item1"
            },
            "345":{
                "_id":2,
                "Label":"Item2"
            }
        }
    }
}

You can test your serializtion using ToJson() extention method, in order to view that all correct and after that use ToBson() if need.您可以使用ToJson()扩展方法测试您的序列化,以便查看所有内容是否正确,然后在需要时使用ToBson()

The problem is that myValueMap derives from Dictionary.问题是 myValueMap 派生自 Dictionary。 That results in a class that the AutoMap method can't handle.这会导致 AutoMap 方法无法处理 class。

I recommend you just use the Dictionary directly, as Andrew did in his reply.我建议您直接使用 Dictionary,就像 Andrew 在他的回复中所做的那样。

Ufortunately the myValueMap is an object that I can't easily change, however it turns out, that's pretty easy to create your own (de)serializer....不幸的是,myValueMap 是一个 object,我无法轻易更改它,但事实证明,创建自己的(反)序列化器非常容易......

    public class myValueMapSerializer : IBsonSerializer
    {
        public object Deserialize(Bson.IO.BsonReader bsonReader, System.Type nominalType, System.Type actualType, IBsonSerializationOptions options)
        {
            if (nominalType != typeof(myValueMap)) throw new ArgumentException("Cannot serialize anything but myValueMap");
            var res = new myValueMap();
            var ser = new DictionarySerializer<string, myValue>();
            var dic = (Dictionary<string, myValue>)ser.Deserialize(bsonReader, typeof(Dictionary<string, myValue>), options);

            foreach (var item in dic)
            {
                res.Add(item.Key, item.Value);
            }
            return res;
        }

        public object Deserialize(Bson.IO.BsonReader bsonReader, System.Type nominalType, IBsonSerializationOptions options)
        {
            throw new Exception("Not implemented");
        }

        public bool GetDocumentId(object document, out object id, out IIdGenerator idGenerator)
        {
            id = null;
            idGenerator = null;
            return false;
        }

        public void Serialize(Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
        {
            if (nominalType != typeof(myValueMap)) throw new ArgumentException("Cannot serialize anything but myValueMap");

            var ser = new DictionarySerializer<string, myValue>();
            ser.Serialize(bsonWriter, typeof(DictionarySerializer<string, myValue>), value, options);
        }

        public void SetDocumentId(object document, object id)
        {
            return;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 com.mongodb.DBObject / Java的BSON序列化器 - com.mongodb.DBObject / BSON serializer for java 在Jackson中使用自定义序列化程序序列化嵌套对象时,发生JsonGenerationException - JsonGenerationException when serializing nested object using custom serializer in Jackson 序列化对象图的一部分 - Serializing a part of object graph 无法使用 Newtonsoft 序列化器从 BSON 反序列化具有集合属性的对象 - Can't deserialize object with collection property from BSON using Newtonsoft serializer Django Rest 框架正在使用相同的序列化器以两种不同的方式序列化 object - Django Rest Framework is serializing an object two different ways using the same serializer 使用Javascript序列化器将数据表序列化为JSON时出错 - Error Serializing Datatable Into JSON using Javascript serializer 无法将“MongoDB.Bson.Serialization.Serializers.DateTimeSerializer”类型的对象转换为“MongoDB.Bson.Serialization.IBsonSerializer”类型 - Unable to cast object of type 'MongoDB.Bson.Serialization.Serializers.DateTimeSerializer' to type 'MongoDB.Bson.Serialization.IBsonSerializer` 使用方法和循环参考图在 typescript 中序列化 object - Serializing an object in typescript with methods and a cyclical reference graph StackOverflowException序列化STE EF对象图 - StackOverflowException serializing STE EF object graph 将Enumeration字段序列化为BSON的异常 - Exception serializing Enumeration field to BSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM