您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:JSON 解析入門(NSJSONSerialization 實作)

編輯:iOS 開發綜合

JSON(JavaScript Object Notation)在網路傳輸中幾乎無所不在。它是一種輕量級的資料交換格式,源自 JavaScript 規格的子集,採用完全獨立於語言的純文字格式,易於人眼閱讀撰寫,也非常適合機器解析與產生,傳輸效率相對傳統的 XML 更好。官方網站是 json.org。

最基本的 JSON 結構

{"Name": "FlyElephant"}

Name 是鍵(key),FlyElephant 是值(value),外層用大括號包裹。開發時常需要臨時造資料測試,網路上有不少公開的氣象 API 可以拿來練手,例如 https://m.weather.com.cn/data/101180601.html(把前面的城市編碼換掉就能查其他城市)。

iOS 上的四種解析方案

常見的有 TouchJSON、SBJson、JSONKit 與系統自帶的 NSJSONSerialization。效能表現大致是:

NSJSONSerialization > JSONKit > SBJson > TouchJson

NSJSONSerialization 是 iOS 5 之後系統內建的,其餘三者都是第三方庫。既然現在的裝置幾乎都在 iOS 6 以上,沒有理由再引入外部相依,本文直接用它來說明。

兩個核心方法

/* 由 Foundation 物件產生 JSON 資料;若物件無法產生合法 JSON 會拋出例外 */
+ (NSData *)dataWithJSONObject:(id)obj
                       options:(NSJSONWritingOptions)opt
                         error:(NSError **)error;

/* 由 JSON 資料還原成 Foundation 物件 */
+ (id)JSONObjectWithData:(NSData *)data
                 options:(NSJSONReadingOptions)opt
                   error:(NSError **)error;

常用的 options 有兩個:NSJSONWritingPrettyPrinted 讓輸出的 JSON 帶縮排、便於閱讀;NSJSONReadingMutableLeaves 讓解析出來的容器與字串都是可變的。資料編碼方面,規格支援 UTF-8、UTF-16LE/BE、UTF-32LE/BE,其中 UTF-8 是解析效率最高的,能選就選它。

實作:抓取並解析天氣資料

先在 Storyboard 上放一個 UITextView:

@property (weak, nonatomic) IBOutlet UITextView *myTextView;

在 viewDidLoad 中請求並解析:

// 設定 URL
NSURL *url = [NSURL URLWithString:@"https://m.weather.com.cn/data/101180601.html"];

// 建立請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 取得回應資料
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
                                            returningResponse:nil
                                                        error:nil];

// 解析 JSON
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:responseData
                                                          options:NSJSONReadingMutableLeaves
                                                            error:nil];

// 取出感興趣的欄位並顯示
NSDictionary *weatherResult = [weatherDic objectForKey:@"weatherinfo"];

self.myTextView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況:溫度 %@ %@",
                        ...];

這段程式碼不該直接用在正式專案

範例能跑,但有幾個問題必須指出:

同步請求會凍結 UI。sendSynchronousRequest:returningResponse:error: 會阻塞主線程,網路慢時整個 App 無回應。正式環境請改用 NSURLSession 或非同步的 NSURLConnection。

error 參數傳 nil 是危險的。網路失敗或 JSON 格式錯誤時,JSONObjectWithData: 會回傳 nil,而後續的 objectForKey: 在 nil 上呼叫雖然不會 crash,卻會靜默得到 nil,問題變得難以追查。務必傳入 NSError 並處理。

HTTP 明文傳輸已被 iOS 阻擋。基於 App Transport Security,iOS 9 之後預設不允許明文 HTTP 連線。除錯時可在 Info.plist 暫時放寬,但正式產品應該改用 HTTPS。

較穩妥的寫法骨架如下:

NSURLSession *session = [NSURLSession sharedSession];

[[session dataTaskWithURL:url
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error)
    {
        NSLog(@"請求失敗:%@", error.localizedDescription);
        return;
    }

    NSError *parseError = nil;
    id json = [NSJSONSerialization JSONObjectWithData:data
                                             options:0
                                               error:&parseError];
    if (parseError || ![json isKindOfClass:[NSDictionary class]])
    {
        NSLog(@"JSON 解析失敗:%@", parseError.localizedDescription);
        return;
    }

    // 回到主線程更新 UI
    dispatch_async(dispatch_get_main_queue(), ^{
        // 更新介面
    });
}] resume];

三個關鍵:檢查 error、驗證回傳值的實際型別、以及在主線程更新 UI。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved