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

iOS 中 NSDictionary 與 JSON 字串的雙向轉換:別再用 description

編輯:iOS 開發綜合

和伺服器互動時,JSON 幾乎無所不在。但很多人直覺地想用 [dict description] 把字典轉成字串,結果字串看起來「像」JSON,實際上卻完全不是合法格式。這裡記錄正確做法與兩個方向的 API。

資料從哪來:FMDB 的 resultDictionary

專案中的資料庫存取用了 FMDB,其中一個很方便的 API 能直接把每一列轉成 NSDictionary:

FMResultSet *rs = [db executeQuery:sql, latestObj, nowObj, latestObj, nowObj];
while ([rs next]) {
    [result addObject:[rs resultDictionary]];
}

錯誤做法:description

// 這是錯的
[middle appendString:[row description]];

description 的回傳型別確實是 NSString*,但內容是 NSDictionary 的人類可讀描述格式,不是 JSON。它不會 escape 引號、不會處理巢狀結構,用在 API 上必然出問題。

正確做法:NSDictionary → NSData → NSString

關鍵是 NSJSONSerialization 的 dataWithJSONObject:options:error:——傳入字典,得到 NSData,再轉成字串:

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:row
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];

options 的選擇要看用途:NSJSONWritingPrettyPrinted 適合除錯或需要人閱讀的場合;要送給伺服器時反而不要加,因為多餘的空白與換行會讓 payload 變大。

反方向:NSData → NSDictionary

收到伺服器回應後,用 JSONObjectWithData:options:error: 還原:

NSData *response = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:nil
                                                     error:nil];
NSError *error = nil;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:response
                                                          options:kNilOptions
                                                            error:&error];

NSNumber *code = [jsonArray objectForKey:@"code"];
if ([code intValue] == 0) {
    NSLog(@"添加備份記錄成功");
}

得到的 NSDictionary 就可以當成 JSON object 直接操作。

三個容易忽略的細節

  • JSON 的顶层不一定是字典:JSONObjectWithData: 也可能回傳 NSArray 甚至 NSString、NSNumber。變數命名成 jsonArray 反而更誠實,用 id 接收並 Runtime 判斷型別才是安全做法。
  • error 參數一定要傳:JSON 格式錯誤時這個 API 會回傳 nil,若不檢查 error 就直接取值,只會拿到 nil 然後在更遠的地方崩潰,難以定位。
  • 同步請求不該出現在正式環境:sendSynchronousRequest: 會阻塞主執行緒,弱網下直接造成畫面凍住甚至被系統 watchdog 終止。請改用 NSURLSession 的非同步 API。

實務建議:直接定義 model

長遠來看,與其反覆手動從字典取值,不如定義對應的 model 類別,用 YYModel、Mantle 或 Codable(Swift)做一次轉換。好處是型別由編譯器把關,key 名稱集中管理,也不容易把 NSNull 當成正常值處理。

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