如何使用AFNetworking解析JSON来处理布尔值

时间:2014-02-20 08:35:10

标签: ios objective-c json

我有一些像这样回来的JSON:

"items":[
{
"has_instore_image": false
}
]

如果我输出这样的值:

NSLog(@"has_instore_image val: %@", [item objectForKey:@"has_instore_image"]);

我得到了

has_instore_image val: 0

但如果我这样测试:

if([item objectForKey:@"has_instore_image"]==0){
  NSLog(@"no, there is not an instore image");
}else{
...

总是转到else语句......嗯..你怎么建议我得到BOOL值并测试?我已经在这里阅读了BOOL的问题,我只是感到困惑,这不符合我的预期。

THX

3 个答案:

答案 0 :(得分:5)

NSDictionary的实例方法objectForKey返回id,而不是原始值。

如果它是JSON中的booleanintfloat等类似数字的值,它将被Apple的NSNumber类序列化为NSJSONSerialization和iOS中的大多数/所有其他常见JSON解析器。

如果您想从中获取BOOL值,可以执行以下操作:

BOOL has_instore_image = [[item objectForKey:@"has_instore_image"] boolValue];

答案 1 :(得分:2)

您正在将指针与此处的整数进行比较

 [item objectForKey:@"has_instore_image"]==0

你应该使用

 [item objectForKey:@"has_instore_image"].integerValue==0

另请注意,BOOL NO等于0。

代码中的NSLog语句打印0,但仅因为如果您将NSLog对象作为参数,则会调用对象description

答案 2 :(得分:1)

我建议将这些id类型(从字典中返回)保存到NSNumber。

 NSNumber *boolNum=(NSNumber*)[item objectForKey:@"has_instore_image"];

之后你可以从boolNum获得bool值

[boolNum boolValue]

试试这个

if([boolNum boolValue]==NO){
    NSLog(@"no, there is not an instore image");
 }else
{

 }