Patryk Gołębiowski Patryk Gołębiowski - 1 year ago 127
C# Question

How to convert JSON to BSON using Json.NET

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

Answer Source

PM> Install-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());