63

I have a long string in JSON format, and I want to convert it into a BSONDocument for insertion into a MongoDB database. How do I do the conversion? I'm using the official C# driver.

Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
Journeyman
  • 10,011
  • 16
  • 81
  • 129

3 Answers3

96

The answer is:

string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
    = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
Tom Robinson
  • 8,348
  • 9
  • 58
  • 102
Journeyman
  • 10,011
  • 16
  • 81
  • 129
59
string json = "{ 'foo' : 'bar' }";  
BsonDocument document = BsonDocument.Parse(json);
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
m_hawk13
  • 690
  • 5
  • 5
5

Using Version 2.1 of MongoDB's .NET library

string json = "{'foo' : 'bar' }";
var document = new BsonDocument();
document.Add(BsonDocument.Parse(json));
Michael
  • 239
  • 3
  • 9