The easiest way to convert JSON to BSON in .net world

I just started working on MongoDB. From my JavaScript client, I send the JSON string to the ASP.NET WEB API project. Is it possible to directly use this JSON string and save it in MongoDB? I also want to know if this approach makes sense.

I am going to pass JSON from the client and on the server side read string as

  [System.Web.Mvc.HttpPost] public dynamic SaveData([FromBody] string data) { System.Web.HttpContext.Current.Request.Form[0] return null; } 
+6
source share
3 answers

Try the following:

 string json = "..."; BsonDocument.Parse(json); 
+4
source

Yes, you can. but keep in mind that sending data on the client side without checking user data can lead to security problems (never trust user input) You can do this using insert collection methods. keep in mind that if you don't have _id in your json Mongodb, you will get it for you.

for example, I will create a document in the assembly "test" like this

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

and the result may be something like this

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

Try it!

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

Source: https://habr.com/ru/post/978384/


All Articles