Json parses local and online files (through interfaces)
Parse local files using json
NSString *path =[[NSBundle mainBundle] pathForResource:@“movielist” ofType:@“txt”];
// Specify the second parameter to specify a container to receive parsed data.
NSMutableDictionary *dic =[NSJSONSerialization JSONObjectWithData:data option:NSJSONReadingMutableContainers error:nil];NSMutableArray *movieArr =[NSMutableArray array]; for (NSMutableDictionary *temp in dic[@result]) { Movie *movie =[[Movie alloc] init]; [movie setValuesForKeysWithDictionary:temp]; [movieArr addObject:movie]; [movie release]; }
Original code for parsing online files
NSString * strURL = @ http://api.map.baidu.com/place/v2/search? Query = Bank®Ion = Dalian & output = json & ak = 6e823f587c95f0148c%3539b99295;
A normal URL address cannot contain Chinese characters, but can only contain numbers, 26 uppercase/lowercase letters, and some special symbols, such as &, %, if you encounter a URL with Chinese characters, do not encode the original code first:
NSString *strEncode= [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Next, after the URL meets the requirements, start network requests. network requests are divided into three steps 1. Create an NSURL Based on the prepared URL
NSURL *url =[NSURL URLWithString:strEncode];
2. Send the original code of a request:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
3. Return the data we want, an NSData object
Three parameters: the first parameter is the request just created, the second is the response returned, and the third is the error message.
Original code
NSURLResponse *response = nil; NSError *error =nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Parse the returned data in json format.
Print all the bank names
Original code:
NSMutableDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; for (NSDictionary *dic1 in dic[@results]) { NSLog(@%@,dic1[@name]); }