I have my Json string as
string myjson = "[
{
"col1": "1",
"col2": "2",
"col3": "3"
},
{
"col1": "4",
"col2": "5",
"col3": "6"
},
{
"col1": "7",
"col2": "8",
"col3": "9"
}]";
Problem is : When i am creating bson document it is showing
Cannot convert BsonArray to BsonDocument
This is how I'm creating the BsonDocument :
BsonDocument doc = BsonSerializer.Deserialize<BsonDocument>(myjson);
What should i do?
BsonDocument doc = new BsonDocument();
BsonArray array = BsonSerializer.Deserialize<BsonArray>(myjson);
doc.Add(array);
I didn't try it but it should work.
Edit:
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));
or simply have a values
element inside the document like this:
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) }
};
The best that I could do is this.
You can try convert BsonArray to array of BsonValue, then iterate through that array:
var a = BsonSerializer.Deserialize<BsonArray>(yourjsontext).ToArray();
for (int i = 0; i < a.Length; i++) {
var document = a[i].ToBsonDocument();
// Do whatever necessary
}
Or a cleaner way :
var arrayDocs = BsonSerializer.Deserialize<BsonArray>(myJsonArrayString);
var documents = arrayDocs.Select(val => val.AsBsonDocument);
which will give you an IEnumerable<BsonDocument>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.