Reputation: 8646
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.
Upvotes: 0
Views: 55
Reputation: 49
You can use reflection
JavaScriptSerializer serializer = new JavaScriptSerializer();
var obj = serializer.DeserializeObject(json);
var propery = obj.GetType().GetProperty("Id");
if (propery == null)
return false;
else
return true;
Upvotes: 1
Reputation: 18127
You should check like this for your current structure.
var id = obj["requirements"]["requirement"][0]["Id"];
if(id != null)
return true;
else
return false;
Upvotes: 1