先将JSON串转换成NSString,再转化为NSData,后再转为NSDictionary,再取出其中的NSArray,最后获取所需NSDictionary元素值:
- (void)parseJSON: (void *)param1 {
const char *p_json = NULL;
if (param1) {
p_json = param1;
//NSLog(@"p_json: %s", p_json);
NSString *pauseAdJson = [[NSString alloc] initWithUTF8String:p_json];
//NSLog(@"pauseAdJson: %@", pauseAdJson);
//json解析
NSData *jsonData = [pauseAdJson dataUsingEncoding:NSUTF8StringEncoding];
//NSLog(@"jsonData: %@", jsonData);
NSError *err;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
}
//NSLog(@"jsonDict: %@", jsonDict);
NSArray *pauseAdArray = [jsonDict objectForKey:@"pause_ad"];
//NSLog(@"pauseAdArray: %@", pauseAdArray);
NSURL *pauseAdImageUrl = [NSURL URLWithString: [[pauseAdArray objectAtIndex:0] objectForKey:@"url"]];
// UI的操作必须要到主线程做
[self performSelectorOnMainThread:@selector(pauseAdDownloadandView:) withObject:pauseAdImageUrl waitUntilDone:NO];
}
}
- (void)pauseAdDownloadandView: (NSURL *)imageUrl {
//在playerview中心展现,占playerview一半的大小
CGRect pauseAdViewRect = CGRectMake([playerview bounds].size.width/4,
[playerview bounds].size.height/4,
[playerview bounds].size.width/2,
[playerview bounds].size.height/2);
pauseAdView = [[UIImageView alloc] initWithFrame:pauseAdViewRect];
pauseAdView.layer.masksToBounds = YES;
pauseAdView.layer.cornerRadius = 5.0f;
[pauseAdView setBackgroundColor:[UIColor blackColor]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
pauseAdView.image = image;
[playerview addSubview:pauseAdView];
}