App 與伺服器溝通時,最常見的任務就是把物件結構轉成 JSON 字串送出去。iOS 5 之後,系統內建了 NSJSONSerialization,不必再引入第三方庫,只要呼叫 dataWithJSONObject:options:error:,就能把 Array 與 Dictionary 序列化為 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 轉為字串
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"
}
JSONObjectWithData:options:error: 即可把 JSON 資料還原成 dictionary/array,是解析 API 回應的標準做法。