C#MongoDB:解析Json字符串

C#MongoDB:解析Json字符串,c#,json,mongodb,bson,C#,Json,Mongodb,Bson,假设我有一个大的JSON文件要解析,我想将其反序列化为BsonDocument 假设我想从中获取一个JSON文件 这是我的密码: var weatherAPI_collection = database.GetCollection<BsonDocument>("weather_API"); string json_data = webClient.DownloadString(URL); using (var json_reader = new JsonReader(json_dat

假设我有一个大的JSON文件要解析,我想将其反序列化为BsonDocument

假设我想从中获取一个JSON文件

这是我的密码:

var weatherAPI_collection = database.GetCollection<BsonDocument>("weather_API");
string json_data = webClient.DownloadString(URL);
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)
    {
        Console.WriteLine(value.AsBsonDocument);
        weatherAPI_collection.InsertOne(value.AsBsonDocument);
    }
}

我该怎么办?我犯了什么错误?

如果您只想将收到的文档写入您的MongoDB集合中,那么这就是方法:

string json_data = new WebClient().DownloadString(URL);
weatherAPI_collection.InsertOne(BsonDocument.Parse(json_data));

请更改您的代码,如下所示:

var weatherAPI_collection = database.GetCollection<BsonDocument>("weather_API");
string json_data = webClient.DownloadString(URL);

var docs = BsonSerializer.Deserialize<List<BsonDocument>>(json_data);
weatherAPI_collection.InsertMany(docs);
var weatherAPI_collection=database.GetCollection(“weatherAPI”);
string json_data=webClient.DownloadString(URL);
var docs=BsonSerializer.Deserialize(json_数据);
weatherAPI_collection.InsertMany(文档);
在列表中反序列化取决于您的json数据,若数组中有json数据,则使用列表,否则您可以这样做

var weatherAPI_collection = database.GetCollection<BsonDocument>("weather_API");
string json_data = webClient.DownloadString(URL);

var docs = BsonSerializer.Deserialize<BsonDocument>(json_data);
weatherAPI_collection.InsertOne(docs);
var weatherAPI_collection=database.GetCollection(“weatherAPI”);
string json_data=webClient.DownloadString(URL);
var docs=BsonSerializer.Deserialize(json_数据);
weatherAPI_collection.InsertOne(文档);
在您的代码中,您尝试在BsonValue中转换,它表示一个BsonDocument中的字段

var weatherAPI_collection = database.GetCollection<BsonDocument>("weather_API");
string json_data = webClient.DownloadString(URL);

var docs = BsonSerializer.Deserialize<BsonDocument>(json_data);
weatherAPI_collection.InsertOne(docs);