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?

asked Nov 13, 2015 at 3:34 4,327 4 4 gold badges 34 34 silver badges 60 60 bronze badges

6 Answers 6

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 BsonWriter and BsonReader :

public static string ToBson(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(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(reader); > > 
answered Jul 11, 2017 at 8:39 Matthias Burger Matthias Burger 5,836 7 7 gold badges 54 54 silver badges 105 105 bronze badges

I am looking at this link when BSON was first added to Newtonsoft.Json. link. 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.

Commented May 4, 2018 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.