3

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.
Lost_In_Library
  • 3,265
  • 6
  • 38
  • 70

1 Answers1

3

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.