如何使用 C# Json 元素存在或不存在(使用 Newtonsoft NugetPackages)

How to Json Element is present or not using C# (With Newtonsoft NugetPackages)

我有 Json 文件,我正在尝试解析 json 文件的数据以使用某些数据条件更新数据库,目前我想检查特定元素是否存在或 not.In 我当前的 Json 数据,在操作节点下 accessRef 可以存在于文件中也可以不存在 completely.So 如何检查条件。请给我建议。

下面是 Json 文件

{
   "PLMXML":{
      "language":"en-us",
      "time":"16:50:15",
      "schemaVersion":"6",
      "author":"Development(-2069033203)",
      "date":"2020-05-22",
      "Header":{
             "id":"id1",
             "traverseRootRefs":"#id6",
             "transferContext":"CLM"
          },
      "Operation":{
             "id":"id21",
             "name":"PD_Op2",
             "subType":"BS4_BaOP",
             "accessRefs":"#id18",
             "catalogueId":"70700000209604",
             "ApplicationRef":{
                "application":"Teamcenter",
                "label":"yDX58d4FIpN8QD",
                "version":"yDX58d4FIpN8QD"
             }
          }
      }
} 

低于我正在尝试执行的代码

public void Readjsonfile(string jsondata)
{   var message = JsonConvert.DeserializeObject<plmxmldatamodel>(jsondata);             
    Console.WriteLine("RootRef: " + message.PLMXML.Header.traverseRootRefs);
    Console.WriteLine("OccurenceId: "+message.PLMXML.ProductView.Operation.id);
// I want to check whtether is accessrefs is present or not inside the Operation element
}    
//fuction1
public class Header
{       public string traverseRootRefs { get; set; }    
}
//fuction2
public class Operation
{   public string id { get; set; }
    public string name { get; set; }
    public string subType { get; set; }
    public string accessRefs { get; set; }
    public string catalogueId { get; set; }
}
//fuction3
public class PLMXML
{
    public string language { get; set; }
    public Header Header { get; set; }
    public Operation Operation { get; set; }
}
//fuction4
public class plmxmldatamodel
{
    public PLMXML PLMXML { get; set; }
}

如果 accessRefs 的 empty/null 值是有效的情况(即 ... "'accessRefs':, ..."),那么您可以使用 JSON Path 检查它是否存在:

var jObj = JObject.Parse(jsondata);
if(jObj.SelectToken("$.PLMXML.Operation.accessRefs") != null)
{
    // do what you want to do if accessRefs exists
}

否则只需检查 message.PLMXML.ProductView.Operation.accessRefs 是否为空:

if(message.PLMXML.ProductView.Operation.accessRefs != null)
{
    // do what you want to do if accessRefs exists
}