首页 > 解决方案 > 删除 JArray 的成员

问题描述

我有以下 JSON

[
    {
        "Code": "Global Payroll",
        "Month1": 1,
        "Month2": 0,
        "Month3": 0,
        "Month4": null,
        "Month5": null,
        "Month6": null,
        "Month7": null,
        "Month8": null,
        "Month9": null,
        "Month10": null,
        "Month11": null,
        "Month12": null,
        "YTD": 1,
        "PercentOfTotal": "16.67%"
    },
    {
        "Code": "GV Payroll",
        "Month1": 0,
        "Month2": 0,
        "Month3": 3,
        "Month4": null,
        "Month5": null,
        "Month6": null,
        "Month7": null,
        "Month8": null,
        "Month9": null,
        "Month10": null,
        "Month11": null,
        "Month12": null,
        "YTD": 3,
        "PercentOfTotal": "50.00%"
    }  
]

我想做的是以某种方式从 JSON 中删除 Month4、Month5 等,然后将其转换回字符串。

我尝试查看 JArray.remove 方法,但这会将项目本身从数组中删除。有人可以告诉我如何从 JArray 中完全删除属性。

标签: c#json.net

解决方案


var array = JArray.Parse(json);

foreach (JObject elem in array)
{
   foreach (var elementToRemove in new List<string>() {"Month4", "Month5" })
   {
       elem.Property(elementToRemove).Remove();
    }              
}

var resultJson = array.ToString();

推荐阅读