2014-02-20 35 views
2

我有回來一些這樣的JSON:如何處理布爾值與AFNetworking解析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的問題,只是感到困惑,這不像我預期的那樣工作。

THX

回答

5

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

如果它是一個booleanintfloat,在JSON等類似數量值,它會被蘋果的NSJSONSerialization類和iOS的大多數/所有其他常見的JSON解析器序列化到NSNumber

如果你想獲得BOOL值超出它,你可以做這樣的事情:

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

您在這裏

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

比較指針與整數你應該使用

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

還要指出的是NO一個BOOL等於0

的代碼中的NSLog語句打印出0 ,但僅僅是因爲如果您以NSLog爲對象作爲參數,則會調用對象description

1

我會建議持有這些ID類型(從字典返回)到NSNumber的。

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

後,你可以從boolNum得到布爾值

[boolNum boolValue] 

試試這個

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

}