IOS Development uses JSON to parse network data _ios

Source: Internet
Author: User
Tags comparison table

After a server request, the data returned to the client is typically in JSON format or in XML format (except for file downloads)

This article will first explain JSON parsing.

Body:

About JSON:

JSON is a lightweight data format, typically used for data interchange JSON in a format much like a dictionary and array in objective-c: {"name": "Jack", "Age": 10}

Add:

Note points in the standard JSON format: Key must be in double quotes. (But in Java it's single quotes)

Json-oc's Conversion comparison table

   

Wherein: null--returns the Nsnull type in OC

Use:

There are many kinds of JSON parsing schemes, but (Apple native) Nsjsonserialization performance is the best

Deserialization (JSON--> OC Object), the following example resolves to a Dictionary object

  

Serialization (OC Object--> JSON), note that the value of the dictionary cannot be nil, but it can be passed [nsnull NULL]

  

Not all types can be converted to JSON.

The following is an official Apple rule:

  

Let's take another look at an example:

#import "MainViewController.h" #import "Video.h" #define Kbaseurl @ "Http://192.168.3.252/~apple" @interface Mainvi 
Ewcontroller () @property (Strong, nonatomic) Nsarray *datalist; 
@property (Weak, nonatomic) UITableView *tableview; @end @implementation mainviewcontroller class= "P1" > "412158" snippet_file_name= "blog_20140630_1_3481337" Name= "C" Ode "class=" OBJC > #pragma mark materialized View-(void) Loadview {self.view = [[UIView alloc]initwithframe:[uiscreen] Mains 
  Creen].applicationframe]; 
  1 TableView cgrect frame = self.view.bounds; UITableView *tableview = [[UITableView alloc]initwithframe:cgrectmake (0, 0, frame.size.width, frame.size.height-44) 
  Style:uitableviewstyleplain]; 
  1) data source [TableView setdatasource:self]; 
  2) Agent [TableView setdelegate:self]; 
  ) Set the table height [tableview setrowheight:80]; 
  [Self.view Addsubview:tableview]; 
   
  Self.tableview = TableView; ToolBar Uitoolbar *toolbar = [[Uitoolbar Alloc]initwithframe:cgrectmakE (0, TableView.bounds.size.height, 320, 44)]; 
   
  [Self.view Addsubview:toolbar]; Add toolbar button Uibarbuttonitem *item1 = [uibarbuttonitem alloc]initwithtitle:@ ' load json ' style: 
  Uibarbuttonitemstyledone target:self Action: @selector (Loadjson)]; Uibarbuttonitem *item2 = [[Uibarbuttonitem alloc]initwithtitle:@ ' load xml ' Style:uibarbuttonitemstyledone target:self 
  Action: @selector (Loadxml)]; Uibarbuttonitem *item3 = [[Uibarbuttonitem alloc]initwithbarbuttonsystemitem:uibarbuttonsystemitemflexiblespace 
  Target:nil Action:nil]; 
[ToolBar setitems:@[item3, Item1, Item3, ITEM2, Item3]]; 
#pragma the Mark-uitableview data source method must be implemented for UITableView the following two methods. -(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {return 
Self.dataList.count; This method is called once per fill row. Know that all the rows on the interface are populated. ,-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath {//Use of rechargeable identifiers 
  Query reusable cell static NSString *id = @ "MyCell"; UiTableviewcell *cell = [TableView dequeuereusablecellwithidentifier:id]; 
  if (cell = = nil) {cell = [[UITableViewCell alloc]initwithstyle:uitableviewcellstylesubtitle Reuseidentifier:id]; 
   
  //Set cell content Video *v = Self.datalist[indexpath.row]; 
  Cell.textLabel.text = V.name; 
  Cell.detailTextLabel.text = V.teacher; 
  Load picture//1) synchronously loads the network picture, and the synchronization method thinks that these instructions will not execute until the instruction is complete. NOTE: When developing network applications, do not use the synchronization method to load the picture, otherwise it will seriously affect the user experience//nsstring *imagepath = [NSString stringwithformat:@ "%@%@", Kbaseurl, 
V.imageurl]; 
Nsurl *imageurl = [Nsurl Urlwithstring:imagepath]; 
NSData *imagedata = [NSData Datawithcontentsofurl:imageurl]; 
UIImage *image = [UIImage imagewithdata:imagedata]; 
  //2) Asynchronously Load network picture///The network connection itself has asynchronous commands SendAsync//[Cell.imageview setimage:image]; 
    If the cached image does not exist if (v.cacheimage = = nil) {//Use the default image placeholder, you can guarantee that there is an image and there is a guarantee that there is a place. 
    UIImage *image = [uiimage imagenamed:@ "User_default.png"]; [Cell.imageview Setimage:image]; Use the default image placeholder/open asynchronous connection, plusThe image is loaded because the corresponding table needs to be refreshed after the load is complete [self loadimageasyncwithindexpath:indexpath]; 
  }else {[Cell.imageview setimage:v.cacheimage]; 
  }//[self Loadimageasyncwithurl:imageurl ImageView:cell.imageView]; 
return cell; #pragma mark asynchronously loads the network picture//Because UITableView is reusable, in order to avoid users quickly and frequently refresh the table, resulting in data conflicts, can not directly uiimageview the asynchronous method//The correct solution is to indexpath the table row 
The asynchronous method is passed in, and the specified row is refreshed directly after the finished image is loaded. 
  -(void) Loadimageasyncwithindexpath: (Nsindexpath *) Indexpath {video *v = Self.datalist[indexpath.row];//Remove the row currently being populated 
  NSString *imagepath = [NSString stringwithformat:@ "%@%@", Kbaseurl, V.imageurl]; 
   
  Nsurl *imageurl = [Nsurl Urlwithstring:imagepath]; 
  NSLog (@ "%@%@", url, ImageView); 
  1 request Nsurlrequest *request = [Nsurlrequest Requestwithurl:imageurl]; 2 Connection SendAsync asynchronous request [Nsurlconnection sendasynchronousrequest:request Queue:[nsoperationqueue MainQueue] completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *error) {//uiimage *image = [UIImage imageWithDaTa:data]; 
    [ImageView Setimage:image]; 
    Saves the network data to the cached image. 
    V.cacheimage = [UIImage imagewithdata:data]; 
  Refresh table [Self.tableview Reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationleft]; 
}]; 
  #pragma mark handles the JSON data-(void) Handlerjsondata: (NSData *) data {//json file, [] represents one. Deserializing JSON data//The second parameter is the parsing method, generally using nsjsonreadingallowfragments nsarray *array = [Nsjsonserialization jsonobjectwithdat 
   
  A:data options:nsjsonreadingallowfragments Error:nil]; NSLog (@ "%@", array); 
   
  JSON parsing is the data in the Nsarray format. 
  Tip: If you are developing a network application, you can save the deserialized object to the sandbox for subsequent development. 
  Nsarray *docs = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); 
  NSString *path = [docs[0]stringbyappendingpathcomponent:@ "Json.plist"]; [Array Writetofile:path atomically:yes]; 
   
  The data inside the array is written into the jspn.plist in the sandbox. 
  Assign values to the data list nsmutablearray *arraym = [Nsmutablearray array]; For (nsdictionary *dict in array) {video *video = [VidEO alloc]init]; 
    Assign a value to a video [video setvaluesforkeyswithdictionary:dict]; 
  [Arraym Addobject:video]; 
  } self.datalist = Arraym; 
   
  Refresh table [Self.tableview Reloaddata]; NSLog (@ "%@", Arraym); This sentence will call the inside of the description and nsarray+log inside the Descriptionwithlocale} #pragma mark load JSON-(void) Loadjson {NSLog (@) 
  Load JSON "); Loading data from a Web server nsstring *str = @ "Http://www.baidu.com?format=json"; 
  Here is the Scribble//hint: NSData itself has a synchronization method, but in actual development, do not use the secondary method//When using the NSData synchronization method, can not specify the timeout, if the server connection is not normal, will affect the user experience. 
  NSData *data = [NSData datawithcontentsofurl:[nsurl urlwithstring:str]]; 
  Resume 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 have no meaning in themselves and are used only for tracing debugging. 
    NSString *result = [[NSString alloc]initwithdata:data encoding:nsutf8stringencoding]; 
     
    NSLog (@ "%@", result); 
    When processing network data, do not convert NSData to NSString. 
  [Self handlerjsondata:data]; 
  }else if (data = = Nil && error = = nil) {NSLog (@ "null"); 
  }else {NSLog (@ "%@", error.localizeddescription); 
#pragma mark loads XML-(void) Loadxml {NSLog (@ "load xml"); 
}//-(void) viewdidload//{//[Super Viewdidload]; } @end

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.