通过使用IOS5自带解析类NSJSONSerialization方法解析JSON
// //字典转json // NSDictionary *dict=[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"pangran",@"name",@"male",@"sex",@"23",@"age" ,nil]; // NSLog(@"%@",dict); // NSError *error; // NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; // NSString *strInfo=[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; // NSLog(@"%@",strInfo); // // // // //json转字典 // // NSData *dataInfo=[strInfo dataUsingEncoding:NSUTF8StringEncoding]; // id jsonObject=[NSJSONSerialization JSONObjectWithData:dataInfo options:NSJSONReadingAllowFragments error:&error]; // // NSDictionary *dictOfVlue=(NSDictionary *)jsonObject; // NSLog(@"%@",dictOfVlue); // // [dict release]; NSString *jsonPath=[[NSBundle mainBundle] pathForResource:@"student" ofType:@"json"]; NSData *valueOfJson=[[NSData alloc] initWithContentsOfFile:jsonPath]; NSError *error=nil; NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:valueOfJson options:NSJSONReadingMutableLeaves error:&error]; if (error==nil) { NSLog(@"%@",dict); } NSData *dataInfo=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; NSString *newStr=[[NSString alloc] initWithData:dataInfo encoding:NSUTF8StringEncoding]; NSLog(@"%@",newStr); // [dict release]; [valueOfJson release];
url解析
- (NSArray *)jsonDemoOfUrl{ //从url中取到每一个商品的title值 NSError *error; //加载一个NSURL对象 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://a.meidebi.com/Link-alllist-p-1-pagecount-10"]]; //将请求的url数据放到NSData对象中 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error]; //url数据分为多层(字典套字典,字典套数组) 取到所要结果所在的”层“ (可以使用VisualJSON工具查看取到的结果) NSDictionary *firstData=[dict valueForKey:@"data"]; NSMutableArray *secondList=[firstData valueForKey:@"linklist"]; //把linklist转换成json文件输出 /* NSData *dataInfo=[NSJSONSerialization dataWithJSONObject:secondList options:NSJSONWritingPrettyPrinted error:&error]; NSString *newStr=[[NSString alloc] initWithData:dataInfo encoding:NSUTF8StringEncoding]; NSLog(@"%@",newStr); */ NSMutableArray *arrInfo=[[NSMutableArray alloc] init]; //定义一个数组存放找到的所取的值 for (NSMutableArray *theArr in secondList) { [arrInfo addObject:[theArr valueForKey:@"title"]]; //遍历数组,找到其中的title字段,添加到结果数组中 } return arrInfo; }