下面是该场景;我有一个来自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 [@“消息”]) –