Cómo convertir JSON a BSON usando Json.NET

Cómo convertir JSON a BSON usando Json.NET

El BsonWriter de Newtonsoft.Json está obsoleto.

Debe agregar un nuevo paquete nuget llamado Json.NET BSON (solo busca newtonsoft.json.bson ) y trabajar con BsonDataWriter y BsonDataReader en lugar de BsonWriter y 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);
    }
}

mientras usa json en mi proyecto me di cuenta de que hay una manera simple y dulce de convertir json en un bson documento.

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

ahora puedes usar document como bson en cualquier lugar.

Nota- Estoy usando este document para insertar en MongoDb base de datos.

Espero que esto te ayude.


Creo que esto te servirá

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

También puede echar un vistazo a Serializar en BSON y C#:convertir una cadena JSON en un documento BSON