摘要:
通过美国教育部 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
最佳答案
您可以将要删除的节点添加到不同的集合中,然后将其删除。例如,
static JObject DeNullifier(JObject inputJson)
{
var nodesToRemove = new List<JToken>();
//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>()))
{
nodesToRemove.Add(degree);
}
}
}
foreach(var node in nodesToRemove)
{
node.Remove();
}
return inputJson;
}
关于c# - 如果要删除某些元素,如何迭代 JObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494431/