C#向MongoDB集合插入文档时出错,请求技术支持
问题:将API返回的JSON数组插入MongoDB集合时出错
我从API请求数据,返回的是JSON对象数组,但执行collection.InsertMany(countryList);时触发错误。以下是相关代码、模型和返回数据:
主程序代码
static async Task CountriesAsync() { var apiURL = "https://restcountries.com/v3.1/alpha/tto"; var results = await client.GetStringAsync(apiURL); string connectionString = "mongodb://localhost"; string databaseName = "world"; string collectionName = "countries"; MongoClient dbClient = new MongoClient(connectionString); var database = dbClient.GetDatabase(databaseName); var collection = database.GetCollection<CountryModel>(collectionName); BsonArray countryList = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(results); collection.InsertMany(countryList); // 此处引发错误 }
模型代码片段
namespace CountryMongoDemo.Models { public class CountryModel { public Name? name { get; set;} } public class Name { public string? common { get; set; } public string? official { get; set; } public NativeName? nativeName { get; set; } } public class NativeName { public Eng? eng { get; set; } } public class Eng { public string? official { get; set; } public string? common { get; set; } } }
API返回的JSON数据片段
[{ "name" : { "common" : "Trinidad and Tobago", "official" : "Republic of Trinidad and Tobago", "nativeName" : { "eng" : { "official" : "Republic of Trinidad and Tobago", "common" : "Trinidad and Tobago" } } }, "tld" : [".tt"], "cca2" : "TT", "ccn3" : "780", "cca3" : "TTO", "cioc" : "TTO", "independent" : true, "status" : "officially-assigned", "unMember" : true, "altSpellings" : ["TT", "Republic of Trinidad and Tobago"], "region" : "Americas", "subregion" : "Caribbean", , "population" : 1399491, "gini" : { "1992" : 40.299999999999997 }, "fifa" : "TRI", "car" : { "signs" : ["TT"], "side" : "left" }, "timezones" : ["UTC-04:00"], "continents" : ["North America"], "flags" : { "png" : "https://flagcdn.com/w320/tt.png", "svg" : "https://flagcdn.com/tt.svg" }, "coatOfArms" : { "png" : "https://mainfacts.com/media/images/coats_of_arms/tt.png", "svg" : "https://mainfacts.com/media/images/coats_of_arms/tt.svg" }, "startOfWeek" : "monday", "capitalInfo" : { "latlng" : [10.65, -61.520000000000003] } }]
错误原因及修复方案
1. 核心问题:类型不匹配
你定义的集合是GetCollection<CountryModel>,但InsertMany方法期望接收IEnumerable<CountryModel>类型的参数,而你传入的是BsonArray,两者类型不兼容,直接导致报错。
2. 修复方法
方法一:直接反序列化为List<CountryModel>
把API返回的JSON字符串直接反序列化为CountryModel的列表,这样可以直接传入InsertMany:
// 替换原反序列化和插入代码 List<CountryModel> countryList = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<List<CountryModel>>(results); collection.InsertMany(countryList);
也可以用Newtonsoft.Json进行反序列化:
List<CountryModel> countryList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CountryModel>>(results); collection.InsertMany(countryList);
方法二:将BsonArray转换为CountryModel集合
如果必须保留BsonArray的处理逻辑,可以手动转换类型:
BsonArray countryList = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(results); var countryModels = countryList.Select(bsonDoc => bsonDoc.AsBsonDocument.To<CountryModel>()).ToList(); collection.InsertMany(countryModels);
3. 额外注意事项
- 你提供的JSON片段存在格式错误:
"subregion" : "Caribbean", ,有多余的逗号,这会导致反序列化失败,建议确认实际API返回的JSON格式是否正确,若有此类问题需先修正。 - 当前
CountryModel仅定义了name相关字段,API返回的其他字段(如tld、population等)会被忽略,如果需要保存这些字段,需在模型中补充对应的属性。
内容的提问来源于stack exchange,提问作者ChrisJ
相关产品推荐
相关产品推荐

