Iphone 从服务器端访问JSON
我从服务器收到以下响应:Iphone 从服务器端访问JSON,iphone,json,Iphone,Json,我从服务器收到以下响应: {"_license":false} 当我试图从那里出来时,它会显示null NSString *items = [[parser objectWithString:[request responseString] error:nil] valueForKey:@"_license"]; NSLog(@"response server%@", items); 知道为什么吗?以及如何解决吗?用以下内容替换您的线路: BOOL items = [[[parser obj
{"_license":false}
当我试图从那里出来时,它会显示null
NSString *items = [[parser objectWithString:[request responseString] error:nil] valueForKey:@"_license"];
NSLog(@"response server%@", items);
知道为什么吗?以及如何解决吗?用以下内容替换您的线路:
BOOL items = [[[parser objectWithString:[request responseString] error:nil] valueForKey:@"_license"] boolValue];
试着把你的代码拼凑起来,不要把每件事都写在一行里。然后检查变量是否包含正确的值
NSLog(@"Server response: %@",[request responseString]);
NSError * error = nil;
NSDictionary *response = [parser objectWithString:[request responseString] error:&error]
if (!response)( {
NSLog( @"Error parsing JSON: %@", error);
return;
}
NSLog(@"Dictionary: %@", response);
NSNumber *hasValidLicense = [response objectForKey:@"_license"];
NSLog(@"Has valid license: %@", hasValidLicense);
if ([hasValidLicense boolValue]){
//Yes we have a valid license.
} else {
// No valid license.
}
确认
[request responseString]
包含您期望的字符串。检查-objectWithString:
的返回值。如果是nil
,请检查错误输出参数(并传递有效地址,而不是nil
)。另外,为什么不使用-[NSDictionary objectForKey:
,这是读取字典项的规范方法?请注意,在Cocoa Touch错误处理中。我们应该首先检查返回值,然后检查错误输出参数。@bai我已经编辑了我的答案。文档链接非常有用。如果-boolValue
之前的表达式为nil
,则您的答案无法解决问题。它总是将NO
分配给项目
。