How to convert JSON to BSON using Json.NET

I have a string containing JSON. The only thing I know about this JSON is that it is valid. How to turn this string into BSON?

+5
source share
5 answers

BsonWriter of Newtonsoft.Json deprecated.

You need to add a new nuget package named Json.NET BSON (just search for newtonsoft.json.bson ) and work with BsonDataWriter and BsonDataReader instead of BsonWriter and BsonReader :

 public static string ToBson<T>(T value) { using (MemoryStream ms = new MemoryStream()) using (BsonDataWriter datawriter = new BsonDataWriter(ms)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(datawriter, value); return Convert.ToBase64String(ms.ToArray()); } } public static T FromBson<T>(string base64data) { byte[] data = Convert.FromBase64String(base64data); using (MemoryStream ms = new MemoryStream(data)) using (BsonDataReader reader = new BsonDataReader(ms)) { JsonSerializer serializer = new JsonSerializer(); return serializer.Deserialize<T>(reader); } } 
+3
source

I think this will do the trick for you

 MongoDB.Bson.BsonDocument BSONDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json); 

You can also see Serialize to BSON and C # - Convert JSON String to BSON Document

+4
source

Here! There is a much simpler way to do this:

 BsonDocument doc = BsonDocument.Parse("{\"your\": \"json\", \"string\": \"here\"}"); 
+3
source

https://www.nuget.org/packages/Newtonsoft.Json

PM> Installation package Newtonsoft.Json -Version 7.0.1

 using Newtonsoft.Json.Bson; using Newtonsoft.Json; class Program { public class TestClass { public string Name { get; set; } } static void Main(string[] args) { string jsonString = "{\"Name\":\"Movie Premiere\"}"; var jsonObj = JsonConvert.DeserializeObject(jsonString); MemoryStream ms = new MemoryStream(); using (BsonWriter writer = new BsonWriter(ms)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, jsonObj); } string data = Convert.ToBase64String(ms.ToArray()); Console.WriteLine(data); } } 
+2
source

when using json in my project, I noticed that there is a simple and nice way to convert json to a bson document.

  string json = "{\"Name\":\"Movie Premiere\"}"; BsonDocument document = BsonDocument.Parse(json); 

you can now use document as bson anywhere.

Note. . I use this document to insert into the MongoDb database.

Hoping this helps you.

+2
source

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


All Articles