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
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);
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<T>(BsonDocument data)
{
var content = data.GetElement("_v");
var jsonDataContent= content.Value.AsBsonValue.ToJson();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonDataContent);
}
Most of the Time for this I use, Json.NET
JsonConvert.SerializeObject(obj);
Most of the time that does the trick. If need be you can set some JsonSerializerSettings
In my opinion the best option is to use Newtonsoft.Json.Bson.BsonReader
.
Here a complete example:
public string ToJson(BsonDocument bson)
{
using (var stream = new MemoryStream())
{
using (var writer = new BsonBinaryWriter(stream))
{
BsonSerializer.Serialize(writer, typeof(BsonDocument), bson);
}
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new Newtonsoft.Json.Bson.BsonReader(stream))
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
using (var jWriter = new JsonTextWriter(sw))
{
jWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
jWriter.WriteToken(reader);
}
return sb.ToString();
}
}
}
I think that this should handle all cases correctly (dates, ids, ...).