C Sharper C Sharper - 12 days ago 6
C# Question

Validating Json Keys

I have following 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"
}
]
}
}


I want to check if it contains Id And Desc tags or keys in it.

I tried below code :-

try
{
var obj = Newtonsoft.Json.Linq.JToken.Parse(strInput);

if(obj["Id"]!=null)
return true;
else
return false;
}
catch (JsonReaderException jex)
{
Logger.GetInstance().LogException(jex, jex.StackTrace, Category.General);
return false;
}


But this code gives obj["Id"] as null even if Id is present in Json.

Answer

You should check like this for your current structure.

var id = obj["requirements"]["requirement"][0]["Id"];

if(id != null)
   return true;
else
   return false;
Comments