Reputation: 561
Let's say I have a big JSON file to parse, and I want to deserialize it into BsonDocument.
Let's say I want to fetch a JSON file from yahoo weather API.
Here is my code:
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);
}
}
But I got the error like:
'JSON reader was expecting ':' but found '":"'.'
What should I do? What mistake did I make?
Upvotes: 1
Views: 2186
Reputation: 326
Please change your code like below:
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);
Deserialize in List depend on you json data if json data in array then use list otherwise you can do like
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);
In your code you are try to convert in BsonValue which is representing a field in one BsonDocument
Upvotes: 1
Reputation: 10918
If all you want to do is write the received document into your MongoDB collection then this is the way to go:
string json_data = new WebClient().DownloadString(URL);
weatherAPI_collection.InsertOne(BsonDocument.Parse(json_data));
Upvotes: 1