在 iOS 平台上操作 JSON 並不困難,但其實還有更簡潔的方案——使用 KVC(Key-Value Coding,鍵值編碼)。以下一步步說明它如何簡化資料綁定。
假設你的應用要從 Web 服務取得 JSON 資料,回傳內容如下:
{count: 3, sum: 9.0, average: 3.0}
取得資料後,需呼叫 NSJSONSerialization 的 JSONObjectWithData: 方法,再從反序列化的字典中逐一取值:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; NSLog(@"%d", [[dictionary objectForKey:@"count"] intValue]); // 3 NSLog(@"%.1f", [[dictionary objectForKey:@"sum"] doubleValue]); // 9.0 NSLog(@"%.1f", [[dictionary objectForKey:@"average"] doubleValue]); // 3.0
但這些值相當分散。做開發時,我們往往更希望與強型別的資料對象互動。例如建立一個 Statistics 類別來代表這份資料:
@interface Statistics : NSObject @property (nonatomic) int count; @property (nonatomic) double sum; @property (nonatomic) double average; @end
然後從字典提取值來填充對象,並把這段綁定邏輯封裝進初始化方法中:
- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
self.count = [[dictionary objectForKey:@"count"] intValue];
self.sum = [[dictionary objectForKey:@"sum"] doubleValue];
self.average = [[dictionary objectForKey:@"average"] doubleValue];
}
return self;
}
Statistics *statistics = [[Statistics alloc] initWithDictionary:dictionary];
這種做法可行,也確實把 JSON 映射到了強型別對象,但每個屬性都要手動對應,顯得繁瑣。
更簡單的方案是 KVC。NSObject 的 setValuesForKeysWithDictionary: 方法,能自動把字典中的所有值映射到對象的屬性。如此一來,初始化方法便可大幅簡化:
- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
[self setValuesForKeysWithDictionary:dictionary];
}
return self;
}
只要屬性的名稱與型別恰當即可,這在 Swift 中同樣運作良好:
class Statistics: NSObject {
var count: Int = 0
var sum: Double = 0
var average: Double = 0
init(dictionary: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dictionary)
}
}
若需要自訂屬性名稱的對應,可以重寫 setValue:forKey:。例如伺服器用 mean 代表平均值:
{count: 3, sum: 9.0, mean: 3.0}
- (void)setValue:(id)value forKey:(NSString *)key {
if ([key isEqual:@"mean"]) {
key = @"average";
}
[super setValue:value forKey:key];
}
最後,若伺服器回傳了 Statistics 未定義的欄位(如 median),setValuesForKeysWithDictionary: 會拋出 NSUnknownKeyException。要避免此異常,只需重寫 setValue:forUndefinedKey::
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
// No-op:直接忽略即可
}
透過 KVC,JSON 到數據對象的綁定變得既簡潔又靈活。