iOS開發網路篇—JSON介紹

來源:互聯網
上載者:User

標籤:android   http   os   檔案   資料   io   for   cti   

 一、什麼是JSONJSON是一種輕量級的資料格式,一般用於資料互動伺服器返回給用戶端的資料,一般都是JSON格式或者XML格式(檔案下載除外) JSON的格式很像OC中的字典和數組{"name" : "jack", "age" : 10}{"names" : ["jack", "rose", "jim"]}標準JSON格式的注意點:key必須用雙引號 要想從JSON中挖掘出具體資料,得對JSON進行解析。即把JSON 轉換為 OC資料類型 二、JSON – OC 轉換對照表對照關係 三、JSON解析方案1.在iOS中,JSON的常見解析方案有4種(1)第三方架構:JSONKit、SBJson、TouchJSON(效能從左至右,越差) (2)蘋果原生(內建):NSJSONSerialization(效能最好) 2.NSJSONSerialization的常見方法(1)JSON資料 ——》 OC對象+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error; (2)OC對象 ——》 JSON資料 + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;3.解析來自伺服器的JSON四、部分程式碼範例#import "YYViewController.h"#import "MBProgressHUD+MJ.h"@interface YYViewController ()@property (weak, nonatomic) IBOutlet UITextField *username;@property (weak, nonatomic) IBOutlet UITextField *pwd;- (IBAction)login;@end@implementation YYViewController- (IBAction)login {//    1.提前的表單驗證    if (self.username.text.length==0) {        [MBProgressHUD showError:@"請輸入使用者名稱"];        return;    }    if (self.pwd.text.length==0) {        [MBProgressHUD showError:@"請輸入密碼"];        return;    }//    2.發送請求給伺服器(帶上帳號和密碼)    //添加一個遮罩,禁止使用者操作    [MBProgressHUD showMessage:@"正在努力載入中...."];////    1.佈建要求路徑//    NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];//    NSURL *url=[NSURL URLWithString:urlStr];        // 1.佈建要求路徑    NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要傳遞參數    //    2.建立請求對象    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//預設為get請求    request.timeoutInterval=5.0;//佈建要求逾時為5秒    [email protected]"POST";//佈建要求方法        //佈建要求體    NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];    //把拼接後的字串轉換為data,佈建要求體    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];        //用戶端類型,只能寫英文    [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];    //    3.發送請求    //擷取一個主隊列    NSOperationQueue *queue=[NSOperationQueue mainQueue];    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        //當請求結束的時候調用(有兩種結果,一個是成功拿到資料,也可能沒有拿到資料,請求失敗)        [MBProgressHUD hideHUD];        if (data) {//請求成功            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];            //判斷後,在介面提示登入資訊            NSString *error=dict[@"error"];            if (error) {                [MBProgressHUD showError:error];            }else            {                NSString *success=dict[@"success"];                [MBProgressHUD showSuccess:success];            }        }else   //請求失敗        {            [MBProgressHUD showError:@"網路繁忙,請稍後重試!"];        }    }];    NSLog(@"請求發送完畢");}@end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.