如何处理布尔值与AFNetworking解析JSON
问题描述:
我有回来一些这样的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
答
NSDictionary
的实例方法objectForKey
返回id
,而不是原始值。
如果它是一个boolean
,int
,float
,在JSON等类似数量值,它会被苹果的NSJSONSerialization
类和iOS的大多数/所有其他常见的JSON解析器序列化到NSNumber
。
如果你想获得BOOL
值超出它,你可以做这样的事情:
BOOL has_instore_image = [[item objectForKey:@"has_instore_image"] boolValue];
答
您在这里
[item objectForKey:@"has_instore_image"]==0
比较指针与整数你应该使用
[item objectForKey:@"has_instore_image"].integerValue==0
还要指出的是NO
一个BOOL
等于0
的代码中的NSLog
语句打印出0 ,但仅仅是因为如果您以NSLog
为对象作为参数,则会调用对象description
。
答
我会建议持有这些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
{
}