SharpCoder
SharpCoder

Reputation: 19193

What is the easiest way to convert JSON into BSON in .net world

I just started working on MongoDB. From my JavaScript client I am sending a JSON string to ASP.NET WEB API project. Is it possible to use this JSON string directly and save it into MongoDB? I also want to know whether this approach make sense ?

I am thinking of passing the JSON from client and on the server side read the string as

 [System.Web.Mvc.HttpPost]
    public dynamic SaveData([FromBody] string data)
    {

        System.Web.HttpContext.Current.Request.Form[0]
        return null;
    }

Upvotes: 6

Views: 2754

Answers (3)

Philip
Philip

Reputation: 3424

Try this:

string json = "...";
BsonDocument.Parse(json);

Upvotes: 4

Desmond
Desmond

Reputation: 787

Try this!

string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

Upvotes: 1

Ariel Henryson
Ariel Henryson

Reputation: 1346

Yes you can. but keep in mind that sending client side data without check the user data can lead to security issues (Never Trust The User's Input) You can do this by using the insert Collection Methods. keep in mind that if you will not have _id in your json Mongodb will produced it for you.

for example i will create a document in the "test" Collection like that

db.test.insert(
 {
   "foo":"bar"
 }
);

and the result can be something like that

{
    "_id" : ObjectId("546c9be08e66b0571a5e3965"),
    "foo" : "bar"
}

Upvotes: 0

Related Questions