簡體   English   中英

無法在C#中將BsonArray轉換為BsonDocument

[英]Cannot convert BsonArray to BsonDocument in c#

我有我的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);

我該怎么辦?

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) }
                };

我能做的最好的就是這個。

您可以嘗試將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
}

或更干凈的方法:

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

這將為您提供IEnumerable<BsonDocument>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM