无法在c#中将BsonArray转换为BsonDocument

问题描述 投票:0回答:3

我有我的Json字符串

string myjson = "[
{
    "col1": "1",
    "col2": "2",
    "col3": "3"
},
{
    "col1": "4",
    "col2": "5",
    "col3": "6"
},
{
    "col1": "7",
    "col2": "8",
    "col3": "9"
}]";

问题是:当我创建bson文档时,它正在显示

无法将BsonArray转换为BsonDocument

这就是我创建BsonDocument的方式:

BsonDocument doc = BsonSerializer.Deserialize<BsonDocument>(myjson);

我该怎么办?

c# .net json mongodb mongodb-.net-driver
3个回答
3
投票
BsonDocument doc = new BsonDocument();
BsonArray array = BsonSerializer.Deserialize<BsonArray>(myjson);
doc.Add(array);

我没试过,但它应该工作。

编辑:

        string myjson1 = "{ 'col1': '1', 'col2': '2', 'col3': '3'}";
        string myjson2 = "{ 'col1': '4', 'col2': '5', 'col3': '6'}";
        string myjson3 = "{'col1': '7', 'col2': '8', 'col3': '9'}";

        BsonArray arr = new BsonArray();
        arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson1));
        arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson2));
        arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson3));

或者只是在文档中有一个values元素,如下所示:

string myjson = "[ { 'col1': '1', 'col2': '2', 'col3': '3'},{ 'col1': '4', 'col2': '5', 'col3': '6'},{'col1': '7', 'col2': '8', 'col3': '9'}]";    
var doc = new BsonDocument {
                    { "values", BsonSerializer.Deserialize<BsonArray>(myjson) }
                };

我能做的最好的就是这个。


0
投票

您可以尝试将BsonArray转换为BsonValue数组,然后遍历该数组:

var a = BsonSerializer.Deserialize<BsonArray>(yourjsontext).ToArray();

for (int i = 0; i < a.Length; i++) {
  var document = a[i].ToBsonDocument();
  // Do whatever necessary
}

0
投票

或者更简洁的方式:

var arrayDocs = BsonSerializer.Deserialize<BsonArray>(myJsonArrayString);
 var documents = arrayDocs.Select(val => val.AsBsonDocument);

哪个会给你一个IEnumerable<BsonDocument>

© www.soinside.com 2019 - 2024. All rights reserved.