Convert MongoDB BsonDocument to valid JSON in C#

后端 未结 10 2571
旧巷少年郎
旧巷少年郎 2020-12-01 14:16

I am working with the MongoDB C# driver. I have a BsonDocument with some data which includes some MongoDB-specific types (like ObjectIDs and ISODates). I want t

10条回答
  •  时光取名叫无心
    2020-12-01 15:00

    If the contents of the BSON document is saved as, below

    {
    "Date" : "2019-04-05T07:07:31.979Z",
    "BSONCONTENT" : {
        "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson",
        "_v" : {
            "A" : "XXXX",
            "B" : 234   
               }  
     }     
    

    }

    then it works with generic class.

    private static T ProcessBsonConversion(BsonDocument data)
        {
            var content = data.GetElement("_v");
            var jsonDataContent= content.Value.AsBsonValue.ToJson();
            return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonDataContent);
    
        }
    

提交回复
热议问题