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?
Can I convert BSON to JSON? Converting a BSON Object to a JSON String Use the asString method to convert the BSON document to an extended JSON string. See http://docs.mongodb.org/manual/reference/mongodb-extended-json/ for more information on extended JSON.
We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.
In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten. In other words, last-value-wins. Save this answer.
BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With