Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into LiteDB BsonDocument

I have a string in JSON format, and I want to convert it into a BSONDocument for insertion into a LiteDB database. How do I do the conversion? I'm using LiteDB 5.0.0-beta ( I also tested it in LiteDB v4.1.4 ). Here is the code;

MyHolder holder = new MyHolder
                  {
                    Json = "{\"title\":\"Hello World\"}"
                  };

BsonDocument bsonDocument = BsonMapper.Global.ToDocument(holder.Json);
// bsonDocument returns null in v5, and throws exception in v4.1.4

Another example in mongoDB, you can do this ( Convert string into MongoDB BsonDocument );

string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

What I've also tried so far;

string json = "{ 'foo' : 'bar' }";    
byte[] bytes = Encoding.UTF8.GetBytes(json);
BsonDocument bsonDocument = LiteDB.BsonSerializer.Deserialize(bytes); // throws "BSON type not supported".

And also tried;

BsonDocument bsonDocument = BsonMapper.Global.ToDocument(json); // Returns null bsonDocument.
like image 707
Lost_In_Library Avatar asked Jul 13 '26 02:07

Lost_In_Library


1 Answers

You can use the LiteDB.JsonSerializer to deserialize a string to a BsonValue. This value can then be added (or mapped) into a BsonDocument (and stored):

var bValue = LiteDB.JsonSerializer.Deserialize(jstring);

Just to add an interesting tidbit: You can also deserialize from a (stream)reader directly, like a http request body! (Look up modelbinding in ASP.NET core):

   public sealed class BsonValueModelBinder : IModelBinder
   {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            using (var reader = new StreamReader(bindingContext.HttpContext.Request.Body))
            {
                var returnValue = LiteDB.JsonSerializer.Deserialize(reader);
                bindingContext.Result = ModelBindingResult.Success(returnValue);
            }

            return Task.CompletedTask;
        }
    }

Intuitively you'd expect a BsonValue to only hold 'one' value and its dotnet type. It however (like a BsonDocument) is also a collection of keyvalue pairs. I doubt the answer is still relevant for the original post, but perhaps it will help someone else.

like image 144
Remi fa Sola Avatar answered Jul 14 '26 17:07

Remi fa Sola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!