19

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?

ebvtrnog
  • 4,167
  • 4
  • 31
  • 59

6 Answers6

27

The BsonWriter of Newtonsoft.Json is obsolete.

You need to add a new nuget-package called Json.NET BSON (just search for newtonsoft.json.bson) and work with BsonDataWriter and BsonDataReader instead of BsonWriterand 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);
    }
}
Matthias Burger
  • 5,549
  • 7
  • 49
  • 94
  • I am looking at this link when BSON was first added to Newtonsoft.Json. [link](http://james.newtonking.com/archive/2009/12/26/json-net-3-5-release-6-binary-json-bson-support). _BSON stores binary data directly, avoiding the time overhead and the additional size of base64 encoded text that regular JSON has with binary data._ So what is the need for the base64 to and from conversions? I'm not disagreeing, I have seen these in other code examples as well, I am just confused. – David Wallace May 04 '18 at 13:33
  • Looking at this again, I think I can answer my own question. Precisely because BSON stores binary data directly, anything encoded in BSON format which contains binary data needs to be converted to base64 before it is safe to transmit over IP, whereas Json is completely character based and does not need this. However the claim that BSON avoids the time overhead and additional size of base64 seems a bit disingenuous, given that you will need to do this conversion anyway, further down the line. – David Wallace May 04 '18 at 16:05
  • 2
    Surely IP copes fine with binary data, and it's only http that wants the Base64 encoding? – Chris F Carroll Aug 04 '22 at 09:21
11

while using json in my project i noticed that there are simple and sweet way to convert json into a bson document.

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

now you can use document as bson anywhere.

Note- I am using this document to insert into MongoDb database.

Hoping this will help you.

Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42
7

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

BsonDocument doc = BsonDocument.Parse("{\"your\": \"json\", \"string\": \"here\"}");
Louie Almeda
  • 5,366
  • 30
  • 38
5

I think this will do the trick for you

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

You can also have a look on Serialize to BSON and C# - Converting JSON string to BSON document

Mohit S
  • 13,723
  • 6
  • 34
  • 69
3

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);
        }
    }
MichaelMao
  • 2,596
  • 2
  • 23
  • 54
0

Just another alternative, with the https://www.nuget.org/packages/MongoDB.Bson package, after using MongoDB.Bson;, you can just write byte[] result = someObj.ToBson();

See Deserializing from BsonDocument to string and serializing back to BsonDocument

David
  • 355
  • 1
  • 9