2016-03-08 137 views
0

下面是該場景;我有一個來自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的響應是否包含消息鍵/值對?

+0

U可以簡單地做,如果(JSON [@「消息」]) –

回答

0

感謝@fullofsquirrels我瞭解如何解決問題。

如果一個JSON是一個JSON數組,那麼[NSJSONSerialization]將使它成爲一個NSArray,所以最簡單的方法是檢查我的響應是否是一個數組,或者如果它不是。這是我的解決方案。

if (![jsonResponse isKindOfClass:[NSArray class]]) { 
     NSLog(@"%@", [jsonResponse valueForKey:@"message"]); 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                 message:[jsonResponse valueForKey:@"message"] 
                 delegate:self 
               cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
     [alert show]; 


    } 
else { 
     //consume API 
} 
0

聽起來像你的服務器API返回JSON實體的成功請求的關鍵「消息」,是否正確?如果是這樣的話,也許試試這個:

if (jsonResponse[@"message"] && 
    [jsonResponse[@"message"] isKindOfClass:[NSString class]] && 
    [jsonResponse[@"message"] isEqualToString:@"In lorem ipsum"]) 
{ 
    // Alert 
} 

這應該給你更好的(但不一定完成),對運行時間方差保護的JSON實體的內容作爲一個整體。

+0

我檢查API響應,並出現一條消息,鍵/值唯一的一次,就是當有一些wron –