C# MongoDB complex class serialization

后端 未结 3 1719
鱼传尺愫
鱼传尺愫 2020-12-30 15:45

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

{
    \"name\" : \"value\",
    \"age\": 1,
    \"isFemale\": true,
          


        
3条回答
  •  悲&欢浪女
    2020-12-30 16:29

    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.

    Step #1:

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

    // For the Hobbies object type:
    [BsonIgnore] //ignore this value in MongoDB
    public Dictionary 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> Collection { get; set; }
    
    [JsonIgnore] //ignore this value in the response on Get requests
    [BsonElement(elementName: "Collection")]
    public BsonArray CollectionBson { get; set; }
    

    Step #2

    In my WebAPI controller method for Post

    [HttpPost]
    public override async Task Post([FromBody] Person person)
    {
        var jsonDoc = JsonConvert.SerializeObject(person.Hobbies);
        person.HobbiesBson = BsonSerializer.Deserialize(jsonDoc);
    
        jsonDoc = JsonConvert.SerializeObject(person.Collection);
        person.CollectionBson = BsonSerializer.Deserialize(jsonDoc);
    
        //save
    }
    

    Step #3

    In my Get request I deserialize it back like this:

    [HttpGet("{id?}")]
    public override async Task 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>(bsonDoc);
    
            bsonDoc = BsonExtensionMethods.ToJson(person.CollectionBson);
            person.Collection = JsonConvert.DeserializeObject>>(bsonDoc);bsonDoc);
        }
        return Ok(people);
    }
    

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

提交回复
热议问题