简体   繁体   中英

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

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

You can try this.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM