c# - 如果要删除某些元素,如何迭代 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
解决方案
您可以通过将代码与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
在删除期间避免
推荐阅读
- google-cloud-platform - 访问权限对于更改模板访问容器注册表无效
- github - 为什么谷歌分析不能在 github 页面上托管的网站上运行?
- javascript - 每次页面加载时都会显示导航栏组件
- postgresql - Postgres db 到雪花的迁移
- android-studio - "import proguard.annotation.Keep" => "无法解析符号'annotation'"
- spring-boot - Spring 的 HATEOAS CollectionModelAssembler 不解析属性注入的 RequestMapping 值
- php - 如何在 sql 数据库中清理和存储小数点
- spring - Spring JPA 本机查询从 postgres 的查询中删除了一些列
- .net - 为什么在 Visual Studio 2019 的 Visual Basic 中使用 msgbox 命令时出现错误消息?
- android - 断言失败:第 6075 行 pos 12:'child == _child':不正确