JSON parsing
What is JSON
JSON is a lightweight data format that is typically used for data interaction
Data returned by the server to the client, usually in JSON format or XML format (except for file downloads)
The format of JSON is much like the dictionary and array in OC
{"name"jack", "age10}{"names["jack", "rose", "jim"]}
Note points in the standard JSON format: key must be double-quoted
To dig out specific data from JSON, you have to parse the JSON
JSON conversion to OC data type
JSON–OC Conversion Table
JSON |
OC |
Curly braces {} |
Nsdictionary |
Brackets [] |
Nsarray |
Double quote "" |
NSString |
Number 10, 10.8 |
NSNumber |
JSON parsing scheme
In iOS, there are 4 common parsing scenarios for JSON
Third-party frameworks: Jsonkit, Sbjson, Touchjson (performance from left to right, worse)
Apple native (comes with): Nsjsonserialization (Best performance)
NSJSONSerialization的常见方法//JSONOC对象+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;//OCJSON数据 + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
Parsing JSON from the server
JSON parsing instance
@interface viewcontroller ()@property(Weak,nonatomic)IboutletUitextfield *username;@property(Weak,nonatomic)IboutletUitextfield *pwd;-(ibaction) login;@end @implementation viewcontroller - (void) viewdidload{[SuperViewdidload];additional setup after loading the view, typically from a nib.}- (void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{[ Self. ViewEndediting:YES];} - (ibaction) Login {//1. User name NSString*usernametext = Self. Username. Text;if(Usernametext. Length==0) {[Mbprogresshud showerror:@"Please enter user name"];return; }//2. Password NSString*pwdtext = Self. PWD. Text;if(Pwdtext. Length==0) {[Mbprogresshud showerror:@"Please enter your password"];return; }//3. Send the user name and password to the server (take the HTTP protocol) //Create a URL: request path NSString*URLSTR = [NSStringstringwithformat:@"http://localhost:8080/server/login?username=%@&pwd=%@", Usernametext, Pwdtext];Nsurl*url = [NsurlURLWITHSTRING:URLSTR];//Create a request nsurlrequest*request = [nsurlrequestRequestwithurl:url];//NSLog (@ "Begin---"); //Send a sync request (send a request on the main thread) //queue: Store Completionhandler this taskNsoperationqueue *queue = [Nsoperationqueue mainqueue]; [nsurlconnectionSendasynchronousrequest:request queue:queue Completionhandler: ^ (nsurlresponse *response, NSData *data,Nserror*connectionerror) {//This block will be automatically called when the request is complete 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": "User name does not exist"} //{"Error": "Password is incorrect"}[Mbprogresshud Showerror:error]; }Else{//{"Success": "Login Successful"} NSString*success = dict[@"Success"]; [Mbprogresshud showsuccess:success]; } }];//NSLog (@ "End---");}@end
Example of video JSON data parsing
Model class
#import <foundation/ Foundation.h> @interface video:nsobject/** * ID */ @property (nonatomic, assign) int Id /** * duration */ @property (Nonatomic, assign) int length; /** * Picture (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 <MediaPlayer/MediaPlayer.h> #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= [[NsmutablearrayALLOC] init]; }return_videos;} - (void) viewdidload{[SuperViewdidload];/** loading server's latest video information * / //1. Create a URL Nsurl*url = URL (@"Video");//2. Create a request nsurlrequest*request = [nsurlrequestRequestwithurl:url];//3. Send Request[nsurlconnectionSendasynchronousrequest:request Queue:[nsoperationqueue Mainqueue] completionhandler:^ (NSURLResponse *response, NSData *data,Nserror*connectionerror) {if(Connectionerror | | data = =Nil) {[Mbprogresshud showerror:@"The Internet is busy, please try again later!" "];return; }//parsing 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. VideosAddobject:video]; }//Refresh table[ Self. TableViewReloaddata]; }];}#pragma mark-table view data source- (Nsinteger) TableView: (UITableView*) TableView numberofrowsinsection: (Nsinteger) section{return Self. Videos. Count;} - (UITableViewCell*) TableView: (UITableView*) TableView Cellforrowatindexpath: (Nsindexpath*) indexpath{Static NSString*id = @"Video";UITableViewCell*cell = [TableView dequeuereusablecellwithidentifier:id];if(!cell) {cell = [[UITableViewCellAlloc] Initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:id]; } Hmvideo *video = Self. Videos[Indexpath. Row]; Cell. Textlabel. Text= Video. Name; Cell. Detailtextlabel. Text= [NSStringstringwithformat:@"duration:%d minutes", video. Length];//Show Video Nsurl*url = Hmurl (video. Image); [Cell. ImageViewSd_setimagewithurl:url placeholderimage:[UIImageimagenamed:@"Placehoder"]];returnCell;}#pragma mark-Proxy method- (void) TableView: (UITableView*) TableView Didselectrowatindexpath: (Nsindexpath*) indexpath{//1. Remove the corresponding video modelHmvideo *video = Self. Videos[Indexpath. Row];//2. Create a video playback controller that comes with your system Nsurl*url = URL (video. URL); Mpmovieplayerviewcontroller *PLAYERVC = [[Mpmovieplayerviewcontroller alloc] initwithcontenturl:url];//3. Display Player[ SelfPRESENTVIEWCONTROLLER:PLAYERVC Animated:YESCompletion:Nil];}@end
iOS Development-JSON parsing