我试图过滤json响应并使用过滤的响应来更新我的mongodb集合中的几个文档。Json响应如下所示:
{"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";和"88999796";是订单id。
我想过滤"start_count", "status"one_answers"remains".
我试着解析它们,但它只适用于只有一个订单id,否则响应是"null";
JObject responseObject = JObject.Parse(responseContent);
orderStartCount = responseObject1["start_count"].ToString();
orderStatus = responseObject1["status"].ToString();
orderRemains = responseObject1["remains"].ToString();
我还使用以下代码来更新单个mongodb文档,但我不知道如何使用多个文档和不同的值。
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);
你的JSON对象不是一个集合;这是一本字典。
集合应该是:
[{"charge":"5","start_count":"10","status":"Completed","remains":"90","currency":"USD"},{"charge":"8","start_count":"50","status":"Completed","remains":"50","currency":"USD"},{"charge":"7","start_count":"80","status":"Completed","remains":"20","currency":"USD"}]
区别如下:
- collection被括在
[]
括号中,而dictionary是一个对象{}
。 - 一个集合有无键对象:
[{},{},{}]
,字典需要每个对象的键值对:{"": {}, "": {}, "": {}}
TL:博士;将JSON反序列化为Dictionary<int, Entity>
,其中Entity
是mongoDB集合的一个项目。
我自己修复了这个问题,我只需要通过响应创建一个循环并提取单个值,下面是代码:
JObject responseObject = JObject.Parse(responseContent);
foreach (var order in responseObject)
{
string orderID = order.Key;
string orderStartCount = order.Value["start_count"].ToString();
string orderStatus = order.Value["status"].ToString();
string orderRemains = order.Value["remains"].ToString();
var filter = Builders<BsonDocument>.Filter.Eq("orderID", orderID);
var update = Builders<BsonDocument>.Update.Set("status", orderStatus)
.Set("start_count", orderStartCount)
.Set("remains", orderRemains);
MyCollection.UpdateOne(filter, update);
}