Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将字符串转换为LiteDB bSondDocument_C#_Json_Nosql_Litedb - Fatal编程技术网

C# 将字符串转换为LiteDB bSondDocument

C# 将字符串转换为LiteDB bSondDocument,c#,json,nosql,litedb,C#,Json,Nosql,Litedb,我有一个JSON格式的字符串,我想将其转换为BSONDocument,以便插入到LiteDB数据库中。我如何进行转换?我使用的是LiteDB 5.0.0-beta(我还在LiteDB v4.1.4中进行了测试)。这是代码 MyHolder holder = new MyHolder { Json = "{\"title\":\"Hello World\"}" }; BsonDocum

我有一个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中的另一个示例中,您可以这样做()

也试过了,

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

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

只需添加一个有趣的小贴士:您还可以直接从(流)读取器反序列化,比如http请求体!(在ASP.NET core中查找modelbinding):

直观地说,您希望BsonValue只包含“一”个值及其dotnet类型。然而,它(像BsonDocument一样)也是键值对的集合。我怀疑这个答案是否仍然适用于原来的帖子,但也许它会帮助其他人

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.
var bValue = LiteDB.JsonSerializer.Deserialize(jstring);
   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;
        }
    }