4

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?

tektiv
  • 14,010
  • 5
  • 61
  • 70
Pranay Deep
  • 1,371
  • 4
  • 24
  • 44
  • your json starts with square brackets, which shows that the object is an array, but bsondocument.parse excepts it to be a valid json object (BsonDocument). You should create BsonDocument like this: http://stackoverflow.com/a/6274023/1817929 – Burak Karakuş Jun 02 '16 at 10:51
  • Same problem, BsonSerializer.Deserialize(myjson) expects myjson to be of BsonDocument format (JSON object), but it is of BsonArray format (JSON array) – Burak Karakuş Jun 02 '16 at 10:54
  • ok now i am getting it, so what should i do now? Actually i am getting that string myjson, so how should i create BsonDocument out of that string? – Pranay Deep Jun 02 '16 at 10:59
  • see my answer below. – Burak Karakuş Jun 02 '16 at 11:01
  • 1
    @BurakKarakuş thank you for this gem `BsonSerializer.Deserialize(myjson)` – JJS Aug 10 '17 at 22:55

3 Answers3

5
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.

Burak Karakuş
  • 1,368
  • 5
  • 20
  • 43
2

Or a cleaner way :

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

which will give you an IEnumerable<BsonDocument>

nphias
  • 591
  • 4
  • 7
0

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
}
AJ Meyghani
  • 4,389
  • 1
  • 31
  • 35
lhmt
  • 21
  • 3