IOS development-JSON Parsing
JSON Parsing
What is JSON
JSON is a lightweight data format and is generally used for data interaction.
The data that the server returns to the client is generally in JSON or XML format (except for file downloads)
JSON format is similar to the dictionary and array in OC.
{"name" : "jack", "age" : 10}{"names" : ["jack", "rose", "jim"]}
Note: The key must use double quotation marks in the standard JSON format.
To Mine Specific data from JSON, parse JSON
Convert JSON to OC Data Type
JSON-OC conversion table
JSON |
OC |
Braces {} |
NSDictionary |
Brackets [] |
NSArray |
Double quotation marks (") |
NSString |
Number 10, 10.8 |
NSNumber |
JSON resolution scheme
In iOS, there are four common JSON resolution solutions.
Third-party frameworks: JSONKit, SBJson, and TouchJSON (performance from left to right, the worse)
Apple native (built-in): NSJSONSerialization (Best Performance)
Common NSJSONSerialization Methods // JSON data to OC object + (id) JSONObjectWithData :( NSData *) data options :( NSJSONReadingOptions) opt error :( NSError **) error; // OC object to JSON Data + (NSData *) dataWithJSONObject :( id) obj options :( NSJSONWritingOptions) opt error :( NSError **) error;
Parse JSON from server
JSON parsing instance
@ Interface ViewController () @ property (weak, nonatomic) IBOutlet UITextField * username; @ property (weak, nonatomic) IBOutlet UITextField * pwd;-(IBAction) login; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib .} -(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {[self. view endEditing: YES]; }-(IBAction) login {// 1. username NSString * usernameText = self. username. text; if (usernameText. length = 0) {[MBProgressHUD showError: @ "enter username"]; return;} // 2. password NSString * pwdText = self. pwd. text; if (pwdText. length = 0) {[MBProgressHUD showError: @ "Enter Password"]; return;} // 3. send the user name and password to the server (HTTP protocol) // create a URL: Request Path NSString * urlStr = [NSString stringWithFormat: @ "http: // localhost: 8080/Server/login? Username = % @ & pwd = % @ ", usernameText, pwdText]; NSURL * url = [NSURL URLWithString: urlStr]; // create a request for NSURLRequest * request = [NSURLRequest requestWithURL: url]; // NSLog (@ "begin ---"); // send a synchronous request (send the request in the main thread) // queue: store the completionHandler task into * queue = [NSOperationQueue mainQueue]; [NSURLConnection failed: request queue: queue completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {// this block will automatically call if (connectionError | data = nil) {[MBProgressHUD showError: @ "request failed"]; return ;} // parse the JSON data returned by the server NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; NSString * error = dict [@ "error"]; if (error) {// {"error": "The user name does not exist"} // {"error": "Incorrect password"} [MBProgressHUD showError: error];} else {// {"success": "Logon successful"} NSString * success = dict [@ "success"]; [MBProgressHUD showSuccess: success] ;}}]; // NSLog (@ "end ---");} @ end
Video JSON data parsing instance
Model class
# Import
@ Interface Video: NSObject/*** ID */@ property (nonatomic, assign) int id;/*** duration */@ property (nonatomic, assign) int length; /*** image (video) */@ property (nonatomic, copy) NSString * image;/*** video name */@ property (nonatomic, copy) NSString * name; /*** video playback path */@ property (nonatomic, copy) NSString * url; + (instancetype) videoWithDict :( NSDictionary *) dict; @ end
#import "Video.h"@implementation Video+ (instancetype)videoWithDict:(NSDictionary *)dict{ Video *video = [[self alloc] init]; [video setValuesForKeysWithDictionary:dict]; return video;}@end
# Import
# Define Url (path) [NSURL URLWithString: [NSString stringWithFormat: @ "http: // localhost: 8080/Server/% @", path] @ interface VideosViewController () @ property (nonatomic, strong) NSMutableArray * videos; @ end @ implementation VideosViewController-(NSMutableArray *) videos {if (! _ Videos) {self. videos = [[NSMutableArray alloc] init];} return _ videos;}-(void) viewDidLoad {[super viewDidLoad]; /** load the server's latest video information * // 1. create a url nsurl * url = Url (@ "video"); // 2. create a request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. send the request [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSEr Ror * connectionError) {if (connectionError | data = nil) {[MBProgressHUD showError: @ "the network is busy. Please try again later! "]; Return;} // parse JSON data NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; NSArray * videoArray = dict [@" videos "]; for (NSDictionary * videoDict in videoArray) {HMVideo * video = [HMVideo videoWithDict: videoDict]; [self. videos addObject: video];} // refresh the table [self. tableView reloadData] ;}] ;}# pragma mark-Table view data source-(NSInteger) t AbleView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. videos. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {static NSString * ID = @ "video"; UITableViewCell * cell = [tableView preview: ID]; if (! Cell) {cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: ID];} HMVideo * video = self. videos [indexPath. row]; cell. textLabel. text = video. name; cell. detailTextLabel. text = [NSString stringWithFormat: @ "Duration: % d minutes", video. length]; // displays the video NSURL * url = HMUrl (video. image); [cell. imageView sd_setImageWithURL: url placeholderImage: [UIImage imageNamed: @ "placehoder"]; return cell;} # pragma mark-proxy method-(void) tableView :( UITableView *) tableView didSelectRowAtIndexPath :( NSIndexPath *) indexPath {// 1. obtain the corresponding video model HMVideo * video = self. videos [indexPath. row]; // 2. create the NSURL * url = Url (video. url); MPMoviePlayerViewController * playerVc = [[MPMoviePlayerViewController alloc] initWithContentURL: url]; // 3. display player [self presentViewController: playerVc animated: YES completion: nil];} @ end