Patryk Gołębiowski Patryk Gołębiowski - 4 days ago 6
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

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

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

            Console.WriteLine(data);
        }
    }
Comments