後端回傳的資料格式以 JSON 為主流。iOS 內建了 NSJSONSerialization,幾行程式碼就能把原始資料轉成字典或陣列。本文記錄解析流程與型別對應關係。
{ } → NSDictionary(字典)[ ] → NSArray(陣列)"..." → NSString(字串)11 / 11.1 → NSNumbertrue / false → NSNumbernull → NSNull(注意:這也是一個物件,並不是 nil)最後一點特別容易踩坑:取值後若不判斷就當字串用,遇到 null 會執行期崩潰。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 建立要請求的位址
NSURL *url = [NSURL URLWithString:
@"https://122.22.222.122:32812/login?username=sky5156&pwd=sky5156&type=JSON"];
// 2. 建立請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 非同步發送,在回呼中處理結果
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 4. 解析:data 是要轉換的內容,options 決定解析規則
// NSJSONReadingMutableContainers 基本規則,產生可變容器
// NSJSONReadingMutableLeaves 產生可變字串(實測有問題,不建議)
// NSJSONReadingAllowFragments 允許頂層不是字典或陣列的片段
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
NSLog(@"%@", dict);
}];
}
@end

字典內容已成功取出。
NSJSONReadingMutableContainers 即可,它保證外層容器是可變的,後續增刪資料方便。NSJSONReadingAllowFragments 只在頂層不是標準容器(例如直接回傳一個字串或數字)時才需要。JSONObjectWithData: 的結果可能是字典、也可能是陣列,取用前最好用 isKindOfClass: 確認。NSURLSession dataTaskWithRequest:completionHandler:,寫法更簡潔且功能更完整。掌握了「JSON ↔ 集合類」的型別對應,加上一層模型轉換(把字典映射為自訂物件的屬性),網路層的資料處理基本就通了。