和伺服器互動時,JSON 幾乎無所不在。但很多人直覺地想用 [dict description] 把字典轉成字串,結果字串看起來「像」JSON,實際上卻完全不是合法格式。這裡記錄正確做法與兩個方向的 API。
專案中的資料庫存取用了 FMDB,其中一個很方便的 API 能直接把每一列轉成 NSDictionary:
FMResultSet *rs = [db executeQuery:sql, latestObj, nowObj, latestObj, nowObj];
while ([rs next]) {
[result addObject:[rs resultDictionary]];
}
// 這是錯的 [middle appendString:[row description]];
description 的回傳型別確實是 NSString*,但內容是 NSDictionary 的人類可讀描述格式,不是 JSON。它不會 escape 引號、不會處理巢狀結構,用在 API 上必然出問題。
關鍵是 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 變大。
收到伺服器回應後,用 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 直接操作。
長遠來看,與其反覆手動從字典取值,不如定義對應的 model 類別,用 YYModel、Mantle 或 Codable(Swift)做一次轉換。好處是型別由編譯器把關,key 名稱集中管理,也不容易把 NSNull 當成正常值處理。