Search code examples
c#.netmongodbserializationbson

MongoDB .NET: Converting Json to BsonArray


I have a Json file looked like this

{
"CompanyStructure":{
"Version": 1,
"Structure_base":{
   "Employee": "Emp_ID",
   "Jobs": "Job_ID",
   "Contacts": "Contact_form"
                    },
"Structure_1":{
    "Employee": "xyz",
    "Jobs": "1",
    "Contacts": "Home"
              },
"Franchise_X":{
     "Number": "100",
     "Location": "NY",
     "Price": "100k",
     "Clients": "Crowded"
              },
}
etc etc

Above is basically a Json file, but I can't deserialize it into BsonArray in order to make a list and put in the database/colletion Here is my code trying to deserialize it

string json_data;
using (var json_reader = new JsonReader(json_data))
            {
                var serializer = new BsonArraySerializer();
                BsonArray bsonArray = serializer.Deserialize(BsonDeserializationContext.CreateRoot(json_reader));
                foreach (BsonValue value in bsonArray)
                {
                    collection.InsertOne(value.AsBsonDocument);
                }
            }

I will always get the Error: "Can't deserialize BsonDocument to BsonArray". Please help me with it. Thank you


Solution

  • For array, your JSON data should be between square brackets. ([...])

    You can try this.

    var json_reader = new JsonReader("[" + json_data + "]"))