首页 > 解决方案 > 如果要删除某些元素,如何迭代 JObject?

问题描述

概括:

通过美国教育部 API,我计划为他们的计算机科学专业的毕业生创建一个大学列表和平均工资。但是,许多学校都有空值,并且尝试删除空值会破坏代码,因为您无法在枚举集合时修改它。

我的取消符代码:

static JObject DeNullifier(JObject inputJson)
{
    //Each school in the results[] section
    foreach(var school in inputJson["results"])
    {
        //Each degree in the cip_4_digit section
        foreach(var degree in school["latest.programs.cip_4_digit"])
        {
            if(string.IsNullOrEmpty(degree["earnings.median_earnings"].Value<string>()))
            {
                degree.Remove();
            }
        }
    }
    return inputJson;
}

JSON 缩短版:

{
    "metadata": 
    {
        "total": 1444,
        "page": 14,
        "per_page": 100
    },

    "results": 
    [
        {
            "school.name": "Georgia College & State University",
            "latest.programs.cip_4_digit": 
            [
                {
                  "earnings.median_earnings": 53200,
                  "title": "Computer Science.",
                  "code": "1107"
                }
            ]
        },
        {
            "school.name": "Georgia Southern University",
            "latest.programs.cip_4_digit": 
            [
                {
                  "earnings.median_earnings": null,
                  "title": "Computer Science.",
                  "code": "1107"
                }
            ]
        }
    ]
}

Newtonsoft JSON.NET 类参考:

https://www.newtonsoft.com/json/help/html/Methods_T_Newtonsoft_Json_Linq_JObject.htm

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JProperty.htm

标签: c#jsoncollectionsjson.net

解决方案


您可以通过将代码与Where标准方法相结合来实现它Linq(无需复制源集合)

static JObject DeNullifier(JObject inputJson)
{
    foreach (var school in inputJson["results"])
    {
        var degrees = (JArray)school["latest.programs.cip_4_digit"];
        var nullDegrees = degrees.Where(t => t["earnings.median_earnings"].Type == JTokenType.Null).ToList();

        foreach (var nullDegree in nullDegrees)
            degrees.Remove(nullDegree);
    }

    return inputJson;
}

您只需选择值为 null 的所有latest.programs.cip_4_digit节点,然后从数组中删除这些项目。earnings.median_earnings

ToList()会将具有空值的令牌提升到新集合中,并有助于InvalidOperationException在删除期间避免


推荐阅读