NSdictionary不是Null,但显示0键/值

时间:2013-02-12 10:45:01

标签: iphone nsdictionary

我使用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 0x9851e00> 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:terminate调用抛出异常

已编辑的代码

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也出现了同样的问题。它在控制台中打印值但为空。

1 个答案:

答案 0 :(得分:0)

错误告诉您,您从JSON检索的属性不是字典而是字符串。看起来json_string不包含有效的JSON对象。

在你的例子中,你也泄漏了:

NSMutableArray *arrAds = [[NSMutableArray alloc]init];
arrAds = [json_dict valueForKey:@"ads"];

您创建一个新的NSMutableArray只是为了将新对象分配给下一行的同一个变量。返回的对象也不是非可变版本。您只需将其替换为:

NSMutableArray *arrAds = [[json_dict objectForKey:@"ads"] mutableCopy];