Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON to BSON using Json.NET

Tags:

c#

json.net

bson

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?

like image 927
Patryk Golebiowski Avatar asked Nov 13 '15 03:11

Patryk Golebiowski


2 Answers

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);
    }
}
like image 70
Matthias Burger Avatar answered Oct 12 '22 15:10

Matthias Burger


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.

like image 29
Vikash Pandey Avatar answered Oct 12 '22 15:10

Vikash Pandey