Search code examples
c#.netmongodbmongodb-.net-driverbson

Convert BSON to valid JSON


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?


Solution

  • 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