13

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?

BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • 2
    I find it odd that ["strict" mode](https://docs.mongodb.org/manual/reference/mongodb-extended-json/) is not the default, but that is the case. At a guess I'd say more users voted for being able to "cut/paste" output directly into the MongoDB shell. – Blakes Seven Feb 11 '16 at 22:40

1 Answers1

14

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

Mainul
  • 879
  • 7
  • 10
  • 1
    I did this, but, when I return this json in api, I get all the trailing \ inside the json. How to manage that? – Vulovic Vukasin Oct 13 '17 at 10:30
  • 5
    Now instead of `"Property" : NumberDecimal("23.44")` i get `"Property" : { "$numberDecimal": "23.44"} ` - Can't it just put the decimal value in the result like a normal person? I just want `"Property" : 23.44` – Piotr Kula Nov 22 '18 at 12:08