iOS 5 後內建了對 JSON 的支援。
我們可以透過 NSJSONSerialization 這個類別將 JSON 格式的字串轉換成 NSArray 或 NSDictionary,
也可以將這兩個類別的物件轉換成 JSON。
NSJSONSerialization 對於資料的格式有一些限制:
1. 只能轉換為 NSArray or NSDictionary
2. 每個 Array or Dictionary 內的元素只能為 NSString、NSNumber、NSArray、NSDictionary、NSNull
3. NSDictionary 的 Key 只能為 NSString
4. NSNumber 不能為 Null
NSJSONSerialization 裡的方法都是靜態方法,大致上可分為兩類:
1. 將資料轉換為 JSON 物件
2. 將 JSON 物件轉換為資料
將資料轉換為 JSON 物件:
1. 將 NSData 物件轉換為 JSON 物件 (NSDictionary or NSArray)
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
ex. 你可以讀取一個 JSON 的字串後,並將之轉換為 NSDictionary
NSString *str = [[NSString alloc] initWithFormat:@"You must got to find your love."];
NSData *data = [kJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSJSONReadingOptions 為轉換時的選項,可以讓你指定轉換後所產生的物件特性。
NSJSONReadingMutableContainers:產生的 Array or Dictionary 為 Mutable 物件
NSJSONReadingMutableLeaves:產生的 String 為 Mutable 物件
NSJSONReadingAllowFragments:允許讀取進來的物件最上層不是 NSArray or NSDictionary
2. 讀取串流物件,並轉換為 JSON:
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;
此 method 可以讀取串流物件,並且轉換成 JSON,但必須自己負責開啓與關閉這個串流
ex.
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://dl.dropbox.com/u/4223444/twLoto.json"]];
NSInputStream *inStream = [[NSInputStream alloc] initWithData:data];
[inStream open];
NSArray *array = [NSJSONSerialization JSONObjectWithStream:inStream options:NSJSONReadingAllowFragments error:nil];
[inStream close];
Question:
1. 同步、非同步使用時機?
同步:當所有資料下載完時,使用者才能繼續動作,期間畫面無論如何都無法動作
非同步:使用者可以一邊下載資料一邊使用 APP,類似 Youtube
2. + (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error ;
何謂串流物件?
與非同步的觀念類似,適合用在需要下載大量資料時,如:音樂、影片等。
我們觀看 Youtube 時,它會讓我們先觀賞已下載好的資料(灰色那條),另一方面一邊下載未完成的資料,
避免使用者等待時間過久,造成負面觀感。
使用串流物件時,一定要使用非同步的方式。