C#MongoDB复杂类序列化 [英] C# MongoDB complex class serialization

查看:95
本文介绍了C#MongoDB复杂类序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#MongoDB驱动程序,并且要保存以下相当复杂的JSON结构:

I'm working with C# MongoDB driver and I have this rather complex JSON struct to save:

{
    "name" : "value",
    "age": 1,
    "isFemale": true,
    "Hobbies" : {
        //All data within the "Hobbies" node is dynamic
        //and may change from one item to another.
        "stringItem" : "value",
        "intItem" : 0.0,
        "listOfItems" : [
            { "field" : 1696.0 }
        ],
        "intArray" : [ 566.0,  1200.0 ]
    },
    "Collection" : [ 
        //All data within the "Collection" node is dynamic
        //and may change from one item to another.
        {
            "field" : "string",
            "FieldTypeId" : 2.0,
            "array" : [ 
                { "value" : "1024x1000" }
            ]
        }
    ]
}

我有代表上述对象的此类:

I have this class that represents the above object:

public class MyClass
{
    public string Name;
    public int Age;
    public bool IsFemale;
    public Dictionary<string, object> Hobbies;
    public List<Dictionary<string, object>> Collection;
}

这是我为兴趣爱好"部分保存的内容:

Here is what I get saved for the "Hobbies" section:

"Hobbies": {
    "stringItem": "value",
    "intItem": 1,
    "listOfItems": {
        "_t": "Newtonsoft.Json.Linq.JArray, Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed",
        "_v": [{
            "_t": "JObject",
            "_v": [{
                "_t": "JProperty",
                "_v": [{
                    "_t": "JValue",
                    "_v": []
                }]
            },
            {
                "_t": "JProperty",
                "_v": [{
                    "_t": "JValue",
                    "_v": []
                }]
            }]
        }]
    }
}

我的猜测是我应该为该类编写一个自定义序列化程序,但在

My guess is that I should write a custom serializer for that class but I couldn't find any useful example in the MONGODB .NET DRIVER Manual

我试图开始并实现这样的东西:

I tried to start and implement something like this:

public class MyClassSerializer : SerializerBase<MyClass>, IBsonDocumentSerializer
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, MyClass value)
    {
        //What to do here???
        base.Serialize(context, args, value);
    }

    public override MyClass Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        //What to do here???
        return base.Deserialize(context, args);
    }

    public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
    {
        switch (memberName)
        {
            case "Name":
                serializationInfo = new BsonSerializationInfo(memberName, new StringSerializer(), typeof(string));
                return true;
            case "Age":
                serializationInfo = new BsonSerializationInfo(memberName, new Int16Serializer(), typeof(string));
                return true;
            case "IsFemale":
                serializationInfo = new BsonSerializationInfo(memberName, new BooleanSerializer(), typeof(string));
                return true;
            case "Hobbies":
                serializationInfo = new BsonSerializationInfo(memberName, new TupleSerializer<string, object>(), typeof(string));
                return true;
            case "Collection":
                serializationInfo = new BsonSerializationInfo(memberName, new ArraySerializer<Dictionary<string, object>>(), typeof(string));
                return true;
            default:
                serializationInfo = null;
                return false;
        }
    }
}

但是我找不到与此有关的任何内容.它尚未完全实现,我读到我需要在某个地方注册序列化程序,但是在哪里...?

But I couldn't find anything to do with this. It is not fully implemented and I read that I need to register the serializer somewhere, but where...?

推荐答案

在此处找到如何将数据保存到MongoDB的方法:

Found how to save the data to MongoDB here: Dictionary-to-BsonDocument conversion omitting _t field and extended it a bit so I thought to share the full solution.

步骤1:

在课堂上,我为每个值声明2个成员:

In my class, I declared 2 members for each value:

// For the Hobbies object type:
[BsonIgnore] //ignore this value in MongoDB
public Dictionary<string, object> Hobbies { get; set; }

[JsonIgnore] //ignore this value in the response on Get requests
[BsonElement(elementName: "Hobbies")]
public BsonDocument HobbiesBson { get; set; }

/*********************************************************************/

// For the Collection object type:
[BsonIgnore] //ignore this value in MongoDB
public List<Dictionary<string, object>> Collection { get; set; }

[JsonIgnore] //ignore this value in the response on Get requests
[BsonElement(elementName: "Collection")]
public BsonArray CollectionBson { get; set; }

第2步

在我的Post

[HttpPost]
public override async Task<IActionResult> Post([FromBody] Person person)
{
    var jsonDoc = JsonConvert.SerializeObject(person.Hobbies);
    person.HobbiesBson = BsonSerializer.Deserialize<BsonDocument>(jsonDoc);

    jsonDoc = JsonConvert.SerializeObject(person.Collection);
    person.CollectionBson = BsonSerializer.Deserialize<BsonArray>(jsonDoc);

    //save
}

第3步

在我的Get请求中,我将其反序列化为:

In my Get request I deserialize it back like this:

[HttpGet("{id?}")]
public override async Task<IActionResult> Get(string id = null)
{
    var people = //get data from mongoDB
    foreach (var person in people)
    {
        var bsonDoc = BsonExtensionMethods.ToJson(person.HobbiesBson);
        person.Hobbies = JsonConvert.DeserializeObject<Dictionary<string, object>>(bsonDoc);

        bsonDoc = BsonExtensionMethods.ToJson(person.CollectionBson);
        person.Collection = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(bsonDoc);bsonDoc);
    }
    return Ok(people);
}

这解决了我的问题,希望它也能对其他人有所帮助:-)

This solved my issue and I hope it can help others as well :-)

这篇关于C#MongoDB复杂类序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆