gpt4 book ai didi

c# - 如何使用 Linq 检查 JSON 中的标签

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:36 25 4
gpt4 key购买 nike

我有以下 JSon 文件:-

{
"requirements": {
"-FileName": "sample.xls",
"requirement": [
{
"desc": "Employee status will be classified as:
• Assigned $ when employee is working on a project.
• Reserved when employee is scheduled to work on a project in near future. Unassigned when employee is not working on project.",
"Id": "Req40"
},
{
"Id": "NFR-2",
"desc": "Team Leader should create resource allocation $% request in Maintain Project Module. Resource allocation request $@is associated with only one role. Project $@ Manager should provide roll-on date and roll-off date in resource allocation request."
},
{
"Id": "req2",
"desc": "PRMS must always be available except during the & @ scheduled maintenance. Scheduled maintenance must always be at 8PM on week days.",
"message": "message of Req3"
}
]
}
}

我想检查 JSON 中是否存在“Id”和“desc”以外的标签。

为此,我使用了如下的 for 循环:-

for (int i = 0; i < NumberOfRequirements; i++)
{
int NumberOfTagsInJson = (obj["requirements"]["requirement"][i]).Count();
if (NumberOfTagsInJson == 2) // checks if tag other than id and desc is present Eg. Message
{
var id = obj["requirements"]["requirement"][i]["Id"];
if (id == null)
{
IsHavingValidTags = false;
break;
}

var Desc = obj["requirements"]["requirement"][i]["desc"];
if (Desc == null)
{
IsHavingValidTags = false;
break;
}
}
else
{
IsHavingValidTags = false;
break;
}
}

如何在不使用 for 循环的情况下优化它。例如。我尝试将其转换为列表:-

(obj["requirements"]["requirement"]).ToList()

在此之后,我想使用 Linq 检查是否存在“Id”和“Desc”以外的标签。

我该如何使用它?

编辑 1

enter image description here

最佳答案

请尝试以下操作:

IsHavingValidTags = obj["requirements"]["requirement"]
.All(_ => _.Count() == 2 && _["Id"] != null && _["desc"] != null);

关于c# - 如何使用 Linq 检查 JSON 中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40734389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com