- (IBAction)JOSNButtonPressed:(id)sender { NSString *str=[@"http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURLURLWithString :str]; // 构造 ASIHTTPRequest 对象 ASIHTTPRequest *request = [ASIHTTPRequestrequestWithURL:url]; // 开始同步请求 [request startSynchronous]; NSError *error = [request error]; assert (!error); // 如果请求成功,返回 Response // 对于2进制数据,使用:responseData NSData *data = [request responseData]; NSString *tmp=[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",tmp); [tmp release]; // 返回一个JSON对象 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; NSArray *songArray = [json objectForKey:@"song"]; NSLog(@"song:%@",songArray); /* NSDictionary *aSony = [songArray objectAtIndex:0]; NSString *array = [aSony objectForKey:@"albumtitle"]; NSLog(@"albumtitle:%@",array); */ // 遍历输出JSON里song里的albumtitle for(NSDictionary *aSony in songArray) { NSString *array = [aSony objectForKey:@"albumtitle"]; NSLog(@"albumtitle:%@",array); } } // 自己构建一个JSON - (IBAction)createaJSON:(id)sender { NSDictionary *song = [NSDictionarydictionaryWithObjectsAndKeys:@"i can fly",@"title",@"4012",@"length",@"Tom",@"Singer", nil]; // isValidJSONObject判断对象是否可以构建成json对象 if ([NSJSONSerializationisValidJSONObject:song]) { NSError *error; // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白,使输出更具可读性。 NSData *jsonData = [NSJSONSerializationdataWithJSONObject:song options:NSJSONWritingPrettyPrintederror:&error]; NSString *json =[[NSStringalloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"json data:%@",json); } }
iPhone下JSON的解析 NSJSONSerialization
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/a64c833db537a4608864d167e91f6c93.html