1

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?

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.