下面是該場景;我有一個來自API的JSON響應。我獲得了API的響應如下:檢查JSON密鑰是否存在
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://apitest.maranatha.org/api/SiteGroupStagings?countryId=%i",[country getCountryID]]]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:token forHTTPHeaderField:@"Token"];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
if (returnData) {
NSDictionary* jsonResponse = [NSJSONSerialization
JSONObjectWithData:returnData options:NSJSONReadingMutableContainers
error:&error];
}
的API將返回對象的JSON數組時的API調用是正確的,返回的是這樣的:
[
{},
{},
...
]
如果有任何問題的處理在服務器側(比缺乏在客戶端因特網連接的其他)請求,從API響應是如下:
{
"message": "In lorem ipsum"
}
我要檢查,如果該鍵/值Pa ir是否存在,以便能夠提醒用戶,而不是嘗試處理會導致發生異常的響應。 我已經嘗試了以下方法,但它似乎不工作,它似乎總是可以找到消息鍵,即使JSON響應是對象數組。
if ([jsonResponse valueForKey:@"message"]) {
NSLog(@"%@", [jsonResponse valueForKey:@"message"]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[jsonResponse valueForKey:@"message"]
delegate:self
cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
else {
//consume the JSON response
}
如何成功檢查來自API的響應是否包含消息鍵/值對?
U可以簡單地做,如果(JSON [@「消息」]) –