我有一个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.发布于 2020-03-13 17:30:20
您可以使用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只包含一个'one‘值和它的dotnet类型。然而,它(类似于BsonDocument)也是键值对的集合。我怀疑答案是否仍然与原始帖子相关,但也许它会对其他人有所帮助。
https://stackoverflow.com/questions/59210669
复制相似问题