JSON is gradually replacing XML as a common format for network data.
Starting with iOS5, use Nsjsonserialization to parse the JSON. There are third-party libraries, such as Sbjson, Jsonkit, Touchjson and so on. From the performance, Nsjsonserizlization best, Jsonkit Second, Sbjson use more widely.
To load the JSON file:
#pragma mark load json-(void) loadjson{NSLog (@ "load json"); Load data from the Web server nsstring *str = @ "Http://www.baidu.com?format=json"; This is a doodle.//Hint: NSData itself has a synchronous method, but in the actual development, do not use the secondary method//When using the NSData synchronization method, cannot specify the time-out period, if the server connection is not normal, will affect the user experience. NSData *data = [NSData datawithcontentsofurl:[nsurl urlwithstring:str]; CV nsurl Nsurl *url = [Nsurl urlwithstring:str]; Establish nsurlrequest nsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy: Nsurlrequestuseprotocolcachepolicy timeoutinterval:2.0f]; Establish Nsurlconnect synchronization method to load data nsurlresponse *response = nil; Nserror *error = nil; Synchronous load Data NSData *data = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:& ERROR]; Error handling if (data! = nil) {//The following two sentences themselves have little meaning and are used only for tracking debugging. NSString *result = [[NSString alloc]initwithdata:data encoding:nsutf8stringencoding]; NSLog (@ "%@", result); Do not convert NSData to nsstring while processing network data. [Self Handlerjsondata:d ATA]; }else if (data = = Nil && error = = nil) {NSLog (@ "null data"); }else {NSLog (@ "%@", error.localizeddescription); }}
The data processed in the resulting nsdata format is parsed into JSON-formatted data.
#pragma mark handles the JSON data-(void) Handlerjsondata: (NSData *) data{ The [] representation of a data in a//json file. //Deserialize JSON data/ * serialization: Convert a Nsboject to serial data for transmission over the Internet. deserialization: Reverses the data obtained on the network to the object we need. */ Nsarray *array = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil]; NSLog (@ "%@", array); JSON parsing is data in nsarray format. }