【问题标题】:Convert string into LiteDB BsonDocument将字符串转换为 LiteDB BsonDocument
【发布时间】:2019-12-06 09:51:12
【问题描述】:

我有一个 JSON 格式的字符串,我想将其转换为 BSONDocument 以插入到 LiteDB 数据库中。我该如何进行转换?我正在使用 LiteDB 5.0.0-beta (我也在 LiteDB v4.1.4 中对其进行了测试)。这是代码;

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

mongoDB中的另一个例子,你可以这样做(Convert string into MongoDB BsonDocument);

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

到目前为止我也尝试过;

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

也试过了;

BsonDocument bsonDocument = BsonMapper.Global.ToDocument(json); // Returns null bsonDocument.

【问题讨论】:

    标签: c# json nosql litedb


    【解决方案1】:

    您可以使用 LiteDB.JsonSerializer 将字符串反序列化为 BsonValue。然后可以将此值添加(或映射)到 BsonDocument 中(并存储):

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

    只是添加一个有趣的花絮:您还可以直接从(流)阅读器反序列化,例如 http 请求正文! (在 ASP.NET 核心中查找模型绑定):

       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;
            }
        }
    

    直观地说,您会期望 BsonValue 仅包含“一个”值及其 dotnet 类型。然而,它(像 BsonDocument 一样)也是键值对的集合。我怀疑答案是否仍然与原始帖子相关,但也许它会对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2019-10-10
      • 2019-01-05
      相关资源
      最近更新 更多