验证Json密钥

时间:2016-11-21 10:53:45

标签: c# .net json

我跟随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"
      }
    ]
  }
}

我想检查它是否包含Id And Desc标签或密钥。

我尝试了以下代码: -

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

但是,即使Json中存在Id,此代码也会将obj [" Id"]视为null。

2 个答案:

答案 0 :(得分:1)

您应该像这样检查您当前的结构。

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

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

答案 1 :(得分:1)

您可以使用反射

JavaScriptSerializer serializer = new JavaScriptSerializer();
var obj = serializer.DeserializeObject(json);

var propery = obj.GetType().GetProperty("Id");
if (propery == null)
    return false;
else
    return true;