Convert MongoDB BsonDocument to valid JSON in C#

后端 未结 10 2540
旧巷少年郎
旧巷少年郎 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

    MongoDB.Bson (2.5+) has support to map between BsonValues and .Net objects. BsonTypeMapper Class

    To map a BsonValue (or BsonDocument) to .Net object use

    var dotNetObj = BsonTypeMapper.MapToDotNetValue(bsonDoc);
    

    You can then use your choice of serialization library. For example,

    JsonConvert.SerializeObject(dotNetObj);
    

    If you have a List of BsonDocument

    var dotNetObjList = bsonDocList.ConvertAll(BsonTypeMapper.MapToDotNetValue);
    

提交回复
热议问题