要把資料送到網路上,JSON 大概是最省事的格式。iOS 內建的 NSJSONSerialization 提供了 dataWithJSONObject:options:error: 方法,直接把 Array 或 Dictionary 轉成 JSON 資料物件,不必再手動拼接字串。
使用上有兩個小細節值得注意:傳入的物件內容必須是 JSON 能表達的型別(字串、數字、陣列、字典、布林與 NSNull),另外 options 帶上 NSJSONWritingPrettyPrinted 會讓輸出的 JSON 帶縮排、可讀性更好;不設這個選項則會產生最精簡的表示法。
- (void)converseToJson {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@"Archy" forKey:@"First Name"];
[dictionary setValue:@"Robbins" forKey:@"Last Name"];
[dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];
NSArray *arrayOfArchysChildren = [[NSArray alloc] initWithObjects:
@"Anthony's Son 1",
@"Anthony's Daughter 1",
@"Anthony's Son 2",
@"Anthony's Son 3",
@"Anthony's Daughter 2", nil];
[dictionary setValue:arrayOfArchysChildren forKey:@"children"];
NSError *error = nil;
// NSJSONWritingPrettyPrinted:讓輸出的 JSON 帶縮排,方便閱讀
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
if ([jsonData length] > 0 && error == nil) {
NSLog(@"Successfully serialized the dictionary into data.");
// NSData 轉成 String
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSLog(@"JSON String = %@", jsonString);
}
else if ([jsonData length] == 0 && error == nil) {
NSLog(@"No data was returned after serialization.");
}
else if (error != nil) {
NSLog(@"An error happened = %@", error);
}
}
2013-05-13 17:14:26.087 ToJsonTest[4890:303] Successfully serialized the dictionary into data.
2013-05-13 17:14:26.089 ToJsonTest[4890:303] JSON String = {
"children" : [
"Anthony's Son 1",
"Anthony's Daughter 1",
"Anthony's Son 2",
"Anthony's Son 3",
"Anthony's Daughter 2"
],
"Age" : 51,
"First Name" : "Archy",
"Last Name" : "Robbins"
}
從輸出可以看到,字典被正確轉成了含嵌套陣列的 JSON 結構,鍵名與值都保留原樣。反過來若要解析,只要用 NSJSONSerialization 的 JSONObjectWithData:options:error: 就能還原成 Dictionary 或 Array,之後照鍵取值即可。
實務上還有一點值得留意:NSJSONSerialization 在遇到不支援的物件型別(例如自訂的 Model 類別)時會直接拋出錯誤,所以自訂類別要先想辦法轉成字典再序列化,並養成檢查 error 的習慣。