我有一个来自 Web 服务器的 JSON 响应,如下所示:
{"success":true, "token":"123456"}
我想在 if 语句中使用它,并将其与“YES”进行比较。
但是,这样做是行不通的:
NSDictionary *response = [response JSONValue]; // the JSON value from webservice response, converted to NSDictionary
if ([response objectForKey:@"success"]){} // does not work
if ([response objectForKey:@"success"] == YES){} // does not work
if ([[response objectForKey:@"success"] integerValue] == YES) {} // does not work...erroneous probably
我该如何解决这个问题? bool 类型转换也会产生警告
最佳答案
由于 [response objectForKey:@"success"]
不起作用,当您尝试 [response valueForKey:@"success"]
时会发生什么?
我怀疑它会返回一个 NSNumber,然后您可以执行以下操作:
NSNumber * isSuccessNumber = (NSNumber *)[response objectForKey: @"success"];
if([isSuccessNumber boolValue] == YES)
{
// this is the YES case
} else {
// we end up here in the NO case **OR** if isSuccessNumber is nil
}
另外,NSLog(@"response dictionary is %@", response);
在您的控制台中是什么样的?我看到您正在使用的 JSON 库 does return NSNumber types for objectForKey
,所以我怀疑您可能没有有效的 NSDictionary。
关于iOS NSDictionary 值确定 bool 值是否来自 JSON bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8266243/