Convert BSON to valid JSON

BanksySan picture BanksySan · Feb 11, 2016 · Viewed 10.7k times · Source

The BsonDocument.ToJson() method returns invalid JSON, as ObjectID() and ISODate are not valid JSON.

What's the best way to get valid JSON from an arbitary BSON document?

Answer

Mainul picture Mainul · Feb 12, 2016

You can try something like this

var document = new BsonDocument("_id", ObjectId.GenerateNewId());
    var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; // key part
    Console.WriteLine(document.ToJson(jsonWriterSettings));

For More info https://groups.google.com/forum/#!topic/mongodb-user/fQc9EvsPc4k