使用C#批量移除JSON中users节点所有条目的activecount属性
C# 批量移除JSON结构中指定字段
待处理原始JSON数据
{ "globals": { "shirt": "red", "shift": "night", "activeUsers": 0 }, "users": { "37328": { "customso": null, "xp": 11872, "hours": 1268.86035, "amount": "0", "hoursannounce": 0, "rank": "Assistant Gamemaster", "active": 0, "activecount": 0, "level": 16, "creditRedeemed": 1, "creditTime": 22.000021, "activeCount": 0 }, "48573": { "customso": null, "xp": 1238, "hours": 12.33921, "amount": "0", "hoursannounce": 0, "rank": "Player", "active": 0, "activecount": 0, "level": 2, "creditRedeemed": 1, "creditTime": 22.000021, "activeCount": 0 }, "38272": { "customso": null, "xp": 4039, "hours": 5.47362, "amount": "0", "hoursannounce": 0, "rank": "Player", "active": 0, "activecount": 0, "level": 4, "creditRedeemed": 1, "creditTime": 3.003343, "activeCount": 0 } } }
需求背景
需要使用C#移除上述JSON中所有用户条目下的activecount字段。目前已经实现单个指定用户节点的字段删除,代码如下:
JObject jo = JObject.Parse(json); JObject header = (JObject)jo.SelectToken("users.37328"); header.Property("activecount").Remove(); json = jo.ToString();
最初考虑先获取users下所有用户条目的列表,通过循环逐个执行上述删除逻辑,但不确定该方案的执行效率是否合理,想确认是否存在更优的一次性处理实现。
验证可用的实现方案
经实际测试,以下遍历子节点的代码可以完美实现需求,遍历操作的性能完全满足常规场景使用,不存在性能瓶颈:
JObject jo = JObject.Parse(json); foreach(var userProp in jo["users"].Children()) { ((JObject)userProp.Last).Property("activecount")?.Remove(); } json = jo.ToString();
内容的提问来源于stack exchange,提问作者Lance Lake
相关产品推荐
相关产品推荐

