C Sharper C Sharper - 13 days ago 6
JSON Question

How to use Linq to check tags within JSon

I have below JSon File :-

{
"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"
}
]
}
}


I want to check if Tags other than "Id" and "desc" are present in JSon.

For this I have used for loop as below :-

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;
}
}


How can I optimize it without using for loop.
Eg. I tried converting it into List as:-

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


After this I wanted to use Linq to check if tags other than "Id" and "Desc" are present.

How can I use it?

EDIT 1

enter image description here

Answer

Please try the following:

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