網路資料交換幾乎離不開 JSON,iOS 生態中可用的解析庫相當多。以下以取得城市天氣資料為例,示範四種常見做法。
需引入標頭:#import <TouchJson/JSON/CJSONDeserializer.h>
// 使用 TouchJson 解析
- (IBAction)btnPressTouchJson:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://m.weather.com.cn/data/101010100.html"];
// 定義 NSError 以捕獲錯誤資訊
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
NSLog(@"jsonString ---> %@", jsonString);
// 以 UTF8 編碼轉為資料,避免取值時亂碼
NSDictionary *rootDic = [[CJSONDeserializer deserializer]
deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
error:&error];
// 回傳的 JSON 有兩層,取出第二層
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo ---> %@", weatherInfo);
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@",
[weatherInfo objectForKey:@"date_y"],
[weatherInfo objectForKey:@"week"],
[weatherInfo objectForKey:@"city"],
[weatherInfo objectForKey:@"weather1"],
[weatherInfo objectForKey:@"temp1"]];
}
需引入標頭:#import <SBJson/SBJson.h>
- (IBAction)btnPressSBJson:(id)sender {
NSURL *url = [NSURL URLWithString:@"https://m.weather.com.cn/data/101180701.html"];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@",
[weatherInfo objectForKey:@"date_y"],
[weatherInfo objectForKey:@"week"],
[weatherInfo objectForKey:@"city"],
[weatherInfo objectForKey:@"weather1"],
[weatherInfo objectForKey:@"temp1"]];
}
不需要引入任何第三方庫,但低於 iOS 5 的系統不支援。
- (IBAction)btnPressIOS5Json:(id)sender {
NSError *error;
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"https://m.weather.com.cn/data/101180601.html"]];
// 同步取得回應資料
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
// 由系統類別解析,options 指定 leaf 為 mutable 方便取值
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response
options:NSJSONReadingMutableLeaves
error:&error];
NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天氣狀況是:%@ %@",
[weatherInfo objectForKey:@"date_y"],
[weatherInfo objectForKey:@"week"],
[weatherInfo objectForKey:@"city"],
[weatherInfo objectForKey:@"weather1"],
[weatherInfo objectForKey:@"temp1"]];
}
實務提醒:sendSynchronousRequest: 會阻塞主執行緒,正式環境應改用 NSURLConnection 的非同步版本或 NSURLSession。
需引入標頭:#import <JSONKit/JSONKit.h>
- (void)btnPressJsonKit:(id)sender {
// 單層 JSON:value 都是字串或數字時,可用 objectFromJSONString
NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@", [data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@", [data1 objectForKey:@"b"]);
// 嵌套 JSON:value 中有 array 或 object 時,
// 建議改用 objectFromJSONStringWithParseOptions:
NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"張三\", \"age\":20}}";
NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
}
如果只需要相容舊系統或已有現成依賴,TouchJSON、SBJson、JSONKit 都能勝任,其中 JSONKit 以速度見長(它是基於 C 撰寫的解析器)。但對於新專案,直接用系統內建的 NSJSONSerialization 就是最合適的選擇:不必引入額外套件、不必處理授權,效能也已經足夠。搭配第三方網路庫時,多數 also 已內建 JSON 解析能力。