I’m trying to filter a json response and use the filtered response to update several documents in my mongodb collection. The Json response looks like this:
{"88996940":{"charge":"5","start_count":"10","status":"Completed","remains":"90","currency":"USD"},
"88996961":{"charge":"8","start_count":"50","status":"Completed","remains":"50","currency":"USD"},
"88999796":{"charge":"7","start_count":"80","status":"Completed","remains":"20","currency":"USD"}}
"88996940","88996961" and "88999796" are the order id’s.
I want to filter the values of "start_count", "status" and "remains".
I tried parsing them but it only works if there is only one order id, otherwise the response is "null":
JObject responseObject = JObject.Parse(responseContent);
orderStartCount = responseObject1["start_count"].ToString();
orderStatus = responseObject1["status"].ToString();
orderRemains = responseObject1["remains"].ToString();
I also used the following code to update a single mongodb document but I don’t know how to do it with multiple documents and different values.
var filterSingle = Builders<BsonDocument>.Filter.Eq("orderID", orderID);
var update = Builders<BsonDocument>.Update.Set("status", orderStatus)
.Update.Set("start_count", orderStartCount)
.Update.Set("remains", orderRemains);
MyCollection.UpdateOne(filterSingle, update);
2
Answers
Fixed the issue myself, I just had to create a loop through the response and extract the single values, here is the code:
Your JSON object is not a collection; it’s a dictionary.
A collection would be:
The differences are:
[]
brackets, whereas dictionary is an object{}
.[{},{},{}]
, a dictionary requires key-value pair for every object:{"": {}, "": {}, "": {}}
TL:DR; Deserialise your JSON into
Dictionary<int, Entity>
, whereEntity
is an item of your mongoDB collection.