C# 将字符串转换为LiteDB bSondDocument
我有一个JSON格式的字符串,我想将其转换为BSONDocument,以便插入到LiteDB数据库中。我如何进行转换?我使用的是LiteDB 5.0.0-beta(我还在LiteDB v4.1.4中进行了测试)。这是代码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
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;
}
}