【发布时间】:2013-02-12 10:45:00
【问题描述】:
我正在使用 json 从服务器获取数据。检查 url 是否收到命中响应,在控制台中打印从 json 获取的所有值。但是字典和尝试使用数组也都通过断点显示空值,但是当在控制台中打印时显示数据被获取。下面是代码。
NSString *urlStr = [NSString stringWithFormat:@"http://server39.pivbfg.com/360ads/apps/ads/%@/android/1360/ord0.9109502528132325?json=1&package_url=%@",self.mStrPid, base64String];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:
[urlStr stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding]]];
NSLog(@"req-------------%@",request);
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
NSLog(@"json_string\n%@",json_string);
NSMutableArray *arrAds = [[NSMutableArray alloc]init];
arrAds = [json_dict valueForKey:@"ads"];
请求正常。 json_string 没问题。 但是 json_dict 在控制台中打印值,但在断点处显示 null。这可能是什么原因。一件事是我正在使用ARC,它会影响这段代码吗?请指导以上。
这是错误:* 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<__nscfstring> valueForUndefinedKey:]:此类不符合关键广告的关键值编码。”* 首先抛出调用栈: (0xb5012 0x13a9e7e 0x13dfb1 0xe565ed 0xdc28db 0xdc288d 0x613d 0x3d1707 0x3d1772 0x320915 0x320caf 0x320e45 0x329e57 0x5942 0x2ed697 0x2edc87 0x2eee8b 0x3001f5 0x30112b 0x2f2bd8 0x2202df9 0x2202ad0 0x2abf5 0x2a962 0x5bbb6 0x5af44 0x5ae1b 0x2ee6ba 0x2f053c 0x544d 0x2b65为0x1) libc++abi.dylib:终止调用抛出异常
修改后的代码
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [json_string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(@"results\n%@",results);
NSMutableArray *arrAds = [[NSMutableArray alloc]init];
arrAds = [results valueForKey:@"ads"];
NSLog(@"dict-------------%@",arrAds);
现在数组 arrAds 也出现了同样的问题。它正在控制台中打印值但为空。
【问题讨论】:
-
你试过像:
NSDictionary *json_dict = (NSDictionary *)[json_string JSONValue]吗?我也发现这可能适用于您的问题:stackoverflow.com/questions/10122534/jsonvalue-arc-issue -
你的错误表明消息发送到
NSCFString实例,所以问题应该在[json_string JSONValue](它返回一个字符串而不是字典) -
可能响应不是有效的 JSON。请在此在线 JSON 验证器门户 www.jsonlint.com 上验证响应字符串“json_string”
-
这里我从@ss1271 引用的链接中获得了解决方案。 [1]:stackoverflow.com/questions/10122534/jsonvalue-arc-issue
-
你在浏览器上的反应是什么>
标签: iphone nsdictionary