我有一个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.
答案 0 :(得分:0)
您可以使用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一样)也是键值对的集合。我怀疑答案是否仍与原始帖子有关,但也许会对其他人有所帮助。