2016-11-21 79 views
0

我有以下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 [email protected] associated with only one role. Project [email protected] 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和說明標籤或鍵。

我嘗試下面的代碼: -

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

但這個代碼提供的obj [ 「ID」]爲空,即使ID出現在JSON。

+3

嗯,是的,你的JSON不包含頂級'Id'屬性 - 它包含了'requirements'要求的屬性,然後有一個'requirement'屬性這是其他對象的數組,每個對象都有一個'Id'屬性。 –

回答

1

你應該檢查你的當前結構。

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

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

或'return id!= null;' –

1

您可以使用反射

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

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