iOS NSDictionary 值确定是否来自 JSON 布尔值的布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8266243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS NSDictionary value determine if Boolean from JSON boolean
提问by yretuta
I have a JSON response from a web server that looks like this:
我有一个来自 Web 服务器的 JSON 响应,如下所示:
{"success":true, "token":"123456"}
and I want to use that in an if statement, and compare it with "YES".
我想在 if 语句中使用它,并将其与“是”进行比较。
However, doing this doesn't work:
但是,这样做不起作用:
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
How can I work around this? Typecasting in Boolean yields a warning too
我该如何解决这个问题?布尔类型转换也会产生警告
回答by Michael Dautermann
since [response objectForKey:@"success"]
does not work, what happens when you try [response valueForKey: @"success"]
?
既然[response objectForKey:@"success"]
不起作用,那么尝试时会发生什么[response valueForKey: @"success"]
?
I suspect it returns a NSNumber and then you can do something like:
我怀疑它返回一个 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
}
Also, what does NSLog( @"response dictionary is %@", response );
look like in your Console? I see the JSON library you're using does return NSNumber types for objectForKey
, so I suspect you might not have a valid NSDictionary.
另外,NSLog( @"response dictionary is %@", response );
在您的控制台中是什么样子的?我看到您使用的 JSON 库确实为 返回 NSNumber 类型objectForKey
,所以我怀疑您可能没有有效的 NSDictionary。
回答by Scott D
An alternative approach to this, which requires no conversion to NSNumber is something like below:
一种不需要转换为 NSNumber 的替代方法如下所示:
if ([response objectForKey:@"success"])
{
if ([[response objectForKey:@"success"] boolValue])
NSLog(@"value is true");
}